How to handle TXT email template using Thymeleaf?

I am trying to send an plain textemail from a Spring application using Thymeleaf.

This is my mail service:

@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);
    }
}

Email is sent and sent to the inbox.

This is my email template plain text:

Token ID: $ {url}

but in the supplied mailbox, the urlvariable is not replaced with a value. What for?

When I use the htmlclassic Thymeleaf HTML syntax, the variable is replaced:

<span th:text="${url}"></span>

What is the correct syntax for an email text template?

+4
source share
2 answers

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

Edit

, , >= 3.0 Thymeleaf:

<properties>
  <thymeleaf.version>3.0.3.RELEASE</thymeleaf.version>
  <thymeleaf-layout-dialect.version>2.1.2</thymeleaf-layout-dialect.version>
</properties>
+9

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, .

0

Source: https://habr.com/ru/post/1666549/


All Articles