一、邮箱设置
启用客户端SMTP服务【qq邮箱】
需要在邮箱里设置启用授权码,点击开始后,会要求验证手机,验证通过后,弹出一个弹框,提示授权码。
设置邮箱配置文件:application.properties,这里的spring.mail.password就是使用获取到的授权码
# MailProperties
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=1716503361@qq.com
spring.mail.password=weuqnlytdaxschcd
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true
二、Spring Email
1.导入jar包
引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.6.3</version>
</dependency>
2.邮箱参数配置****
MailClient.java
发件人、收件人、主题、内容等
@Component
public class MailClient {
private static final Logger logger = LoggerFactory.getLogger(MailClient.class);
@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);
helper.setText(content,true);
mailSender.send(helper.getMimeMessage());
}catch(MessagingException e) {
logger.error("发送邮件失败:" + e.getMessage());
}
}
}
3.使用JavaMailSender发送邮件
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = ResumeApplication.class)
public class MailTest {
@Autowired
private MailClient mailClient;
@Test
public void testSend(){
mailClient.sendMail("1716503361@qq.com","TEST","welcome");
}
}
测试结果:
三、模板引擎
使用Thymeleaf发送HTML邮件
html文件:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件事例</title>
</head>
<body>
<p>欢迎你!<span style="color: red;" th:text="${username}"></span></p>
</body>
</html>
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = ResumeApplication.class)
public class MailTest {
@Autowired
private MailClient mailClient;
@Autowired
private TemplateEngine templateEngine;
@Test
public void testHtmlMail(){
Context context = new Context();
context.setVariable("username","sunday");
String content = templateEngine.process("/mail/demo", context);
System.out.println(content);
mailClient.sendMail("1716503361@qq.com","HTML",content);
}
}
运行结果:
总结
AD 【由@Autowired 注入的】