邮件服务已经是基础性服务了 ,是网站的必备功能之一,当注册了某些网站的时候,邮箱里通常会收到一封注册成功通知邮件或者点击激活账号的邮件,博客园也是如此。本文使用Spring Boot,通过QQ邮箱来模仿博客园发送一封通知邮件。
博客园发送的“欢迎您加入博客园”的主题邮件如图所示。这种通知邮件,只有登录用户名在变化,其它邮件内容均不变,很适合用邮件模板来处理。

模板可以实现显示与数据分离,将模板文件和数据通过模板引擎生成最终的HTML代码。
Thymeleaf是一个适用于Web和独立环境的现代服务器端Java模板引擎,能够处理HTML,XML,JavaScript,CSS甚至纯文本。Thymeleaf由于使用了标签属性做为语法,模版页面直接用浏览器渲染,与其它模板引擎(比如Freemaker)相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。
Thymeleaf作为Spring官方推荐的模板引擎,Spring boot对Thymeleaf支持比较友好,配置简单,这里使用Thymeleaf作为模板引擎。
下面正式开始实现仿博客园发送通知邮件。
1. pom.xml添加邮件和模板相关依赖
<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>
2. application.property配置邮箱和thymelea模板
我使用的是QQ邮箱,需要获得QQ邮箱的授权码。
spring.mail.host=smtp.qq.com spring.mail.username=QQ邮箱 spring.mail.password=授权码 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true #thymelea模板配置 spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.servlet.content-type:text/html #热部署文件,页面不产生缓存,及时更新 spring.thymeleaf.cache=false spring.resources.chain.strategy.content.enabled=true spring.resources.chain.strategy.content.paths=/**
3. 编写Service及其实现
Service中有两个方法:
sendSimpleMail用于发送简单的文本邮件,是一个比较基础的案例。
sendHtmlMail用于发送HTML邮件,发送通知邮件用的就是这个方法。其实模板邮件也就是HTML邮件中的一个子类。
MailService:
public interface MailService { public void sendSimpleMail(String to, String subject, String content); public void sendHtmlMail(String to, String subject, String content); }
MailServiceImpl:
@Component public class MailServiceImpl implements MailService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private JavaMailSender mailSender; @Value("${spring.mail.username}") private

