Springboot 邮件发送实例

1.pom.xml添加依赖:

<!--邮箱依赖-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--thymeleaf模板引擎-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
  <version>2.3.7.RELEASE</version>
</dependency>

2.配置application.properties文件:

########## 邮箱配置 ##########
# smtp服务器地址:
spring.mail.host=XXX
# smtp服务器用户名:
spring.mail.username=XXX
# smtp服务器授权码:
spring.mail.password=XXX
# 设置是否需要认证,如果为true,那么用户名和密码 true:
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

########## Thymelea配置 ##########
# thymeleaf路径
spring.thymeleaf.prefix=classpath:/templates/
# 设置thymeleaf模板后缀
spring.thymeleaf.suffix=.html
# 设置thymeleaf严格校验
spring.thymeleaf.mode=HTML
# 设置thymeleaf编码
spring.thymeleaf.encoding=UTF-8
# 设置thymeleaf类型
spring.thymeleaf.servlet.content-type=text/html
# 是否开启缓存
spring.thymeleaf.cache=false
#启用thymeleaf视图分辨率
spring.thymeleaf.enabled=true

3.编写测试用例:

// 邮件测试
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void sendSimpleMail() throws Exception {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
        Context context = new Context();
        Map<String, Object> map = new HashMap<>();
        map.put("username", "XXX");//Thymelaf模板username内容
        context.setVariables(map);
        String emailContent = templateEngine.process("mailtemplates", context);
        message.setFrom("XXX@qq.com");//收件人
        message.setTo("XXX@qq.com");//收件人邮箱
        message.setSubject("XXX");//主题
        message.setText(emailContent, true);//邮件正文
        javaMailSender.send(mimeMessage);
    }

4.在resources/templates创建mailtemplates.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>邮箱模板</title>
</head>
<body>
    <div>
      <span th:text="${username}" ></span>
    </div>
</body>
</html>

5.运行单元测试

posted @ 2021-02-18 16:27  皮一皮很开心  阅读(123)  评论(0编辑  收藏  举报