最近要在spring boot项目中实现按期发送邮件的功能,boot自己有对jmail实现集成,简单的发送邮件功能也很easy,只要你在工程的项目中添加上所依赖的jar便可。html
这里有个问题:如今网站都比较流行模板应用,发送邮件内容不固定,也想利用相似网页模板格式的形式来实现,thymeleaf作为比较流行的模板引擎,是个不错的选择。spring
网上利用spring boot + thymeleaf来实现发送邮件功能的代码仍是不多的(国内基本没有),其实实现起来也很容易,下面是主要的步骤:网站
1.配置文件须要添加内容:spa
# THYMELEAF (ThymeleafAutoConfiguration)htm
spring.thymeleaf.check-template-location=true模板引擎
spring.thymeleaf.prefix=classpath:/templates/io
# spring.thymeleaf.excluded-view-names= # comma-separated list of view names that should be excluded from resolution模板
#spring.thymeleaf.view-names= # comma-separated list of view names that can be resolvedclass
spring.thymeleaf.suffix=.html配置
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=true
2.在要实现发送邮件的类里添加模板
@Autowired
private SpringTemplateEngine templateEngine;
3.加载内容模板
Context context = new Context(Locale.CHINA);
context.setVariable("data", datas);
String text = templateEngine.process("mail-template", context);
注意,这里不要再添加html后缀,由于在配置文件里已经配置加载的后缀了。
4.接下来就是jmail的实现了,在此就不在冗述。