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=spring.mail.username=*******@#授权码spring.mail.password=***********spring.mail.protocol=smtps# 采用ssl安全连接spring.mail.properties.mail.smtp.ssl.enable=true
4.编辑发送邮件的工具类
@Componentpublic class MailClient {@Autowiredprivate 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格式的,默认是falsehelper.setText(content, true);mailSender.send(helper.getMimeMessage());} catch (MessagingException e) {e.getMessage();}}}
5.编写测试类
@RunWith(SpringRunner.class)@SpringBootTest@ContextConfiguration(classes = CommunityApplication.class)public class MailTests {@Autowiredprivate MailClient mailClient;@Autowiredprivate TemplateEngine templateEngine;@Testpublic void testTextMail() {mailClient.sendMail("**********@", "TEST", "Welcome.");}//发送html页面@Testpublic void testHtmlMail() {Context context = new Context();context.setVariable("username", "*****");//第一个参数为templates目录下的要发送html文件的相对路径String content = templateEngine.process("/mail/demo", context);System.out.println(content);mailClient.sendMail("*********@", "HTML", content);}}
要发送的html页面
<!DOCTYPE html><html lang="en" xmlns:th=""><head><meta charset="UTF-8"><title>Title</title></head><body><h1>Welcome,<span style="color: aqua" th:text="${username}"></span></h1></body></html>