springboot发送邮件(QQ邮箱)

1.获取QQ邮箱授权码

邮箱设置–>账户–>POP3/SMTP服务开启

在这里插入图片描述

2.导入spring mail 和thymeleaf jar包

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-mail</artifactId>
   <version>2.1.5.RELEASE</version>
</dependency>
<!-- thymeleaf模板依赖 -->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>

3.在application.properties配置mail

# 访问邮箱的域名 smtp表示协议
spring.mail.host=smtp.qq.com
spring.mail.username=*******@qq.com
#授权码
spring.mail.password=***********
spring.mail.protocol=smtps
# 采用ssl安全连接
spring.mail.properties.mail.smtp.ssl.enable=true

4.编辑发送邮件的工具类

@Component
public class MailClient {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    public void sendMail(String to, String subject, String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            //第二个参数为true表示邮件正文是html格式的,默认是false
            helper.setText(content, true);
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            e.getMessage();
        }
    }

}

5.编写测试类

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MailTests {

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void testTextMail() {
        mailClient.sendMail("**********@qq.com", "TEST", "Welcome.");
    }

    //发送html页面
    @Test
    public void testHtmlMail() {
        Context context = new Context();
        context.setVariable("username", "*****");

        //第一个参数为templates目录下的要发送html文件的相对路径
        String content = templateEngine.process("/mail/demo", context);
        System.out.println(content);

        mailClient.sendMail("*********@qq.com", "HTML", content);
    }

}

要发送的html页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
   <h1>Welcome,<span style="color: aqua" th:text="${username}"></span></h1>
</body>
</html>
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值