最近要在spring boot项目中实现定期发送邮件的功能,boot本身有对jmail实现集成,简单的发送邮件功能也很easy,只要你在工程的项目中添加上所依赖的jar即可。
这里有个问题:现在网站都比较流行模板应用,发送邮件内容不固定,也想利用类似网页模板格式的形式来实现,thymeleaf做为比较流行的模板引擎,是个不错的选择。
网上利用spring boot + thymeleaf来实现发送邮件功能的代码还是很少的(国内基本没有),其实实现起来也很容易,下面是主要的步骤:
1.配置文件需要添加内容:
# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:/templates/
# 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 resolved
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的实现了,在此就不在冗述。