您的位置:首页 > 编程语言 > Java开发

SpringBoot + Thymeleaf实现邮件发送功能

2016-07-05 00:00 986 查看
摘要: springboot mail实现发送邮件功能,但利用thymeleaf模板来发送邮件内容网络资源还是很少,下面就列下自己所踩过的坑。

最近要在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的实现了,在此就不在冗述。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring boot thymeleaf jmail