如何使用Thymeleaf处理TXT电子邮件模板?

Art*_*gon 8 email spring plaintext thymeleaf

我正在尝试plain text使用Thymeleaf从Spring应用程序发送电子邮件.

这是我的电子邮件服务:

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

电子邮件被发送并发送到邮箱.

这是我的plain text电子邮件模板:

令牌网址:$ {url}

但是在交付的邮箱中,url变量不会被它的值替换.为什么?

当我使用html经典HTML Thymeleaf语法时,变量被替换:

<span th:text="${url}"></span>
Run Code Online (Sandbox Code Playgroud)

电子邮件文本模板的正确语法是什么?

ygl*_*odt 12

您也可以在纯文本模式下使用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
Run Code Online (Sandbox Code Playgroud)

这意味着您可以在其中包含一个文本文件:

Token url: [(${url})]
Run Code Online (Sandbox Code Playgroud)

在这里查看这些功能的完整文档:

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>
Run Code Online (Sandbox Code Playgroud)

  • 是的,你是对的.我使用了来自Spring的Thymeleaf`startet`依赖包,它在版本2.x中添加了Thymeleaf.当我删除版本2并升级到版本3时,语法正常工作,正如您所提到的,它是推荐的方式. (2认同)