SpringBoot(35)之发送邮件

SpringBoot(35)之发送邮件

微信搜索 zze_coding 或扫描 👉 二维码关注我的微信公众号获取更多资源推送:

邮件的自动配置类为 org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration

下面以 QQ 邮箱给 GMail 邮箱发送邮件为例。
1、使用 Maven 创建 SpringBoot 项目,引入 Web 场景启动器。

2、引入 Mail 场景启动器:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

3、获取 qq 邮箱授权码,登录进入 qq 邮箱,进入设置,选择账户,选择生成授权码:

image.png

4、邮箱相关配置:

# application.properties
spring.mail.username=632404164@qq.com
// 使用生成的授权码
spring.mail.password=nffutccjfabdbchc
spring.mail.host=smtp.qq.com

# qq 邮箱需要开启 ssl
spring.mail.properties.mail.smtp.sll.enable=true

5、测试:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MailApplicationTests {

    @Autowired
    JavaMailSender javaMailSender;

    // 发送普通文本内容
    @Test
    public void test1() {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        // 设置邮件标题
        mailMessage.setSubject("标题");
        // 设置邮件内容
        mailMessage.setText("hello");

        mailMessage.setFrom("632404164@qq.com");
        mailMessage.setTo("zhangzhongen326@gmail.com");
        javaMailSender.send(mailMessage);
                 

    }

    // 发送 html 内容带附件
    @Test
    public void test2() throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        // 设置标题
        mimeMessageHelper.setSubject("标题");
        // 设置内容
        mimeMessageHelper.setText("<font color='red'>hello</font>",true);

        // 设置附件,可设置多个
        mimeMessageHelper.addAttachment("1.jpg", new File("C:\\Users\\Administrator\\Desktop\\1mail.png"));

        mimeMessageHelper.setFrom("632404164@qq.com");
        mimeMessageHelper.setTo("zhangzhongen326@gmail.com");
        javaMailSender.send(mimeMessage);  
    }
}

image.png

image.png

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://www.zze.xyz/archives/springboot35.html

Buy me a cup of coffee ☕.