1.要点:
- 邮箱设置
- Spring Email
- 导入Jar包
- 邮箱参数设置
- 使用JavaMailSender发送邮件
- 模板引擎
- 使用Thymeleaf发送html邮件(包括图片和链接)
2.使用Spring Email
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>version</version>
</dependency>
# 详情见MailProperties类
# 设置邮箱host
spring.mail.host=smtp.163.com
#邮箱端口
spring.mail.port=465
# 邮箱基本设置
spring.mail.username=邮箱登录名
spring.mail.password=授权码(开通SMTP或IMAP服务时的授权码)
# smptps 最后的s代表安全的协议
spring.mail.protocol=smtps
# 开启ssl安全连接
spring.mail.properties.mail.smtp.ssl.enable=true
- 使用SpringJavaMailSender发送邮件
@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);
} catch (MessagingException e) {
LOGGER.error("邮件发送失败:" + e.getMessage());
}
}
}
@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("目标邮箱", "test", "test");
}
@Test
public void testHtmlMail(){
Context context = new Context();
context.setVariable("username", "zhangsan");
String content =
templateEngine.process("模板的路径(相对于Template文件夹的路径)", context);
System.out.println(content);
mailClient.sendMail("目标邮箱", "testHtml", content);
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件示例</title>
</head>
<body>
<p>Welcome, <span style="color: #ff6547" th:text="${username}"></span>!</p>
</body>
</html>