新建spring boot 应用
通过Spring Initializr 新建一个spring boot 应用,然后在idea中打开,在原有pom中额外添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
创建配置文件
resources/application.properties
#mail
spring.mail.host=smtp.163.com
spring.mail.username=修改成自己邮箱账号
spring.mail.password=修改成自己邮箱密码
spring.mail.default-encoding=UTF-8
#thymeleaf
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.vm
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
邮件模版,模版中有一个变量username
resources/templates/email-template.vm
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Java Mail</title>
</head>
<body>
<h3>你好:<span th:text="${username}"></span></h3>
<p>welcome to use thymeleaf.</p>
</body>
</html>
创建领域对象
@Data
public class MailMessage {
/**
* 邮件模版
*/
private String templateId;
/**
* 邮件变量
*/
private Map<String, Object> paramMap;
/**
* 邮件主题
*/
private String subject;
/**
* 发送者
*/
private String from;
/**
* 抄送
*/
private List<String> copyList;
/**
* 接收者
*/
private List<String> toList;
}
创建服务
public interface MailService {
boolean send(MailMessage message);
}
创建服务实现
@Service
public class MailServiceImpl implements MailService {
private static final Logger LOGGER = LoggerFactory.getLogger(MailServiceImpl.class);
@Autowired
private JavaMailSender sender;
@Autowired
private SpringTemplateEngine templateEngine;
/**
* https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/integration.html#mail-usage-mime
*
* @param message
* @return
*/
@Override
public boolean send(MailMessage message) {
// TODO 参数校验...
try {
//构造消息
MimeMessage mimeMessage = buildMimeMessage(message);
//发送
sender.send(mimeMessage);
} catch (Exception e) {
LOGGER.error("send mail error", e);
return false;
}
return true;
}
private MimeMessage buildMimeMessage(MailMessage message) throws Exception {
MimeMessage mimeMessage = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//主题
helper.setSubject(message.getSubject());
//发送者
helper.setFrom(message.getFrom());
//接受者
helper.setTo(message.getToList().toArray(new String[0]));
//抄送
if (!CollectionUtils.isEmpty(message.getCopyList())) {
helper.setCc(message.getCopyList().toArray(new String[0]));
}
Context context = new Context(Locale.CHINA);
context.setVariables(message.getParamMap());
//解析模版
String content = templateEngine.process(message.getTemplateId(), context);
helper.setText(content, true);
return mimeMessage;
}
}
启动应用
@SpringBootApplication
public class MailApplication implements CommandLineRunner {
@Autowired
private MailService mailService;
public static void main(String[] args) {
SpringApplication.run(MailApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
MailMessage mailMessage = new MailMessage();
mailMessage.setTemplateId("email-template");
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("username", "张三");
mailMessage.setParamMap(paramMap);
mailMessage.setFrom("修改成发送者邮箱");
mailMessage.setToList(Arrays.asList("修改成接收者邮箱"));
mailMessage.setSubject("Hello Spring Boot Java Mail");
mailService.send(mailMessage);
}
}
检查接收者邮箱
可以看到已经收到了邮件,并且模版中的username也替换成了: “张三”