Spring 如何使用Thymeleaf处理TXT电子邮件模板?
我正试图用Thymeleaf从Spring应用程序发送Spring 如何使用Thymeleaf处理TXT电子邮件模板?,spring,email,thymeleaf,plaintext,Spring,Email,Thymeleaf,Plaintext,我正试图用Thymeleaf从Spring应用程序发送纯文本电子邮件 这是我的电子邮件服务: @Override public void sendPasswordToken(Token token) throws ServiceException { Assert.notNull(token); try { Locale locale = Locale.getDefault(); final Context ctx = new Context
纯文本
电子邮件
这是我的电子邮件服务:
@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);
}
}
电子邮件被发送并传递到邮箱中
这是我的纯文本
电子邮件模板:
令牌url:${url}
但在传递的邮箱url
中,变量不会替换为它的值。为什么?
当我使用html
classic html-Thymeleaf语法时,变量被替换:
<span th:text="${url}"></span>
电子邮件文本模板的正确语法是什么?使用这样的HTML模板,它将生成纯文本
<html xmlns:th="http://www.thymeleaf.org" th:inline="text" th:remove="tag">
Token url: [[${url}]]
</html>
令牌url:[${url}]]
另一种方式,仍然使用html可能是这样的
<span th:text="Token url:" th:remove="tag"></span><span th:text="${url}" th:remove="tag"></span>
您正在寻找的是生成
纯文本
,因此thymeleaf将为您返回该文本。您也可以在纯文本模式下使用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})]
请在此处查看这些功能的完整文档:
编辑
如评论中所述,确保使用Thymeleaf的版本>=3.0:
<properties>
<thymeleaf.version>3.0.3.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.2</thymeleaf-layout-dialect.version>
</properties>
3.0.3.1发布
2.1.2
这是一种正确的方法。我的意思是一种有效的方法,我不确定这是否是官方的,我知道它是有效的。注意,当使用[[]]语法时,文本将是html转义的:为什么它被否决了?这是版本3的一个很好的补充,正如问题所述。谢谢你发帖。是的,你是对的。我使用了Spring的Thymeleafstarter
dependency包,它在2.x版中添加了Thymeleaf。当我删除版本2并升级到版本3时,语法正在运行,正如您所提到的,这是推荐的方法。