邮箱设置–>账户–>POP3/SMTP服务开启
2.导入spring mail 和thymeleaf jar包3.在application.properties配置mailorg.springframework.boot spring-boot-starter-mail 2.1.5.RELEASE org.springframework.boot spring-boot-starter-thymeleaf
# 访问邮箱的域名 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=true4.编辑发送邮件的工具类
@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页面
Title
Welcome,



