1. 构建环境
在pom.xml
中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
在application.properties
中添加以下依赖:
spring.mail.host=smtp.gmail.com #以Gmail为例
spring.mail.port=587
spring.mail.username=邮箱用户名
spring.mail.password=邮箱密码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
此处可能会遇到Gmail的权限认证问题,需要开启权限许可。
至此,环境构建完毕。
2. 写一个工具类
写一个用于发送邮件的工具类:
@Component
public class EmailTool {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String senderMailAddress;
@Autowired
private TemplateEngine templateEngine;
public void sendSimpleMail(Map<String, Object> valueMap){
MimeMessage mimeMessage = null;
try {
mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
// 设置发件人邮箱
helper.setFrom(senderMailAddress);
// 设置收件人邮箱
helper.setTo((String[])valueMap.get("to"));
// 设置邮件标题
helper.setSubject(valueMap.get("title").toString());
// 添加正文(使用thymeleaf模板)
Context context = new Context();
context.setVariables(valueMap);
String content = this.templateEngine.process("mail", context);
helper.setText(content, true);
// 添加附件
if (valueMap.get("filePathList") != null) {
String[] filePathList = (String[]) valueMap.get("filePathList");
for(String filePath: filePathList) {
FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, fileSystemResource);
}
}
// 发送邮件
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
HTML模板文件mail.html
如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${title}"></div>
<div th:text="${content}"></div>
</body>
</html>
3. 测试用例
@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailToolTest {
@Autowired
private EmailTool emailTool;
@Test
public void sendSimpleMail() {
String[] filePath = new String[]{"C:\\01.jpg"};
Map<String, Object> valueMap = new HashMap<>();
valueMap.put("to", new String[]{"接收邮箱1", "接收邮箱2"});
valueMap.put("title", "邮件标题");
valueMap.put("content", "邮件内容");
valueMap.put("filePathList", filePath);
emailTool.sendSimpleMail(valueMap);
}
}
亲测无误。