提问人:jnemecz 提问时间:1/12/2017 最后编辑:Rayweb_onjnemecz 更新时间:3/29/2018 访问量:15064
如何使用 Thymeleaf 处理 TXT 电子邮件模板?
How to process TXT e-mail template with Thymeleaf?
问:
我正在尝试使用 Thymeleaf 从 Spring 应用程序发送电子邮件。plain text
这是我的电子邮件服务:
@Override
public void sendPasswordToken(Token token) throws ServiceException {
Assert.notNull(token);
try {
Locale locale = Locale.getDefault();
final Context ctx = new Context(locale);
ctx.setVariable("url", url(token));
// Prepare message using a Spring helper
final MimeMessage mimeMessage = mailSender.createMimeMessage();
final MimeMessageHelper message = new MimeMessageHelper(
mimeMessage, false, SpringMailConfig.EMAIL_TEMPLATE_ENCODING
);
message.setSubject("Token");
message.setTo(token.getUser().getUsername());
final String content = this.textTemplateEngine.process("text/token", ctx);
message.setText(content, false);
mailSender.send(mimeMessage);
} catch (Exception e) {
throw new ServiceException("Token has not been sent", e);
}
}
电子邮件已发送并传递到邮箱。
这是我的电子邮件模板:plain text
令牌 url:${url}
但在已传递邮箱中,变量不会替换为它的值。为什么?url
当我使用经典的 HTML Thymeleaf 语法时,变量被替换:html
<span th:text="${url}"></span>
电子邮件文本模板的正确语法是什么?
答:
3赞
Rayweb_on
1/12/2017
#1
使用这样的 HTML 模板,它将产生纯文本。
<html xmlns:th="http://www.thymeleaf.org" th:inline="text" th:remove="tag">
Token url: [[${url}]]
</html>
另一种方式,仍然使用 HTML 可能是这样的
<span th:text="Token url:" th:remove="tag"></span><span th:text="${url}" th:remove="tag"></span>
你要做的是生产,所以百里香叶会为你返回。plain text
评论
1赞
Rayweb_on
1/12/2017
这是一种正确的方法。我的意思是一种有效的方法,我不确定这是否是官方的,我知道它有效。
2赞
eugene82
11/7/2019
请注意,当使用 [[]] 语法时,文本将被 html 转义:thymeleaf.org/doc/tutorials/3.0/...
24赞
yglodt
1/13/2017
#2
您也可以在纯文本模式下使用 Thymeleaf,如下例所示:
Dear [(${customer.name})],
This is the list of our products:
[# th:each="p : ${products}"]
- [(${p.name})]. Price: [(${#numbers.formatdecimal(p.price,1,2)})] EUR/kg
[/]
Thanks,
The Thymeleaf Shop
这意味着你可以有一个文本文件,里面只有这个:
Token url: [(${url})]
请在此处查看这些功能的完整文档:
https://github.com/thymeleaf/thymeleaf/issues/395
编辑
正如评论中提到的,请确保使用 Thymeleaf 的 >= 3.0 版本:
<properties>
<thymeleaf.version>3.0.3.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.2</thymeleaf-layout-dialect.version>
</properties>
评论
0赞
Rayweb_on
1/13/2017
正如问题所述,这是对版本 3 的一个很好的补充。感谢您发布它。
2赞
jnemecz
1/13/2017
是的,你是对的。我使用了 Spring 的 Thymeleaf 依赖包,它在 2.x 版本中添加了 Thymeleaf。当我删除版本 2 并升级到版本 3 时,语法正在起作用,正如您提到的,这是推荐的方式。starter
评论