Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process TXT e-mail template with Thymeleaf?

I'm trying to send plain text email from Spring application with Thymeleaf.

This is my e-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 delivered into mailbox.

This is my plain text email template:

Token url: ${url}

but in delivered mailbox url variable is not replaced with it's value. Why?

When I use html classic HTML Thymeleaf syntax, variable is replaced:

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

What is proper syntax for e-mail text template?

like image 911
Artegon Avatar asked Jan 11 '17 20:01

Artegon


2 Answers

Use an HTML template like this and it will procude plain text.

<html xmlns:th="http://www.thymeleaf.org" th:inline="text" th:remove="tag">
Token url: [[${url}]]
</html>

another way, still using html could be like this

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

What you are looking is to produce plain text so thymeleaf will return that for you.

like image 195
Rayweb_on Avatar answered Nov 15 '22 16:11

Rayweb_on


You can use Thymeleaf in plain text mode as well, like in this example:

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

That means you can have a text-file with just this in it:

Token url: [(${url})]

Take a look at the complete documentation of those features here:

https://github.com/thymeleaf/thymeleaf/issues/395

Edit

As mentioned in a comment, make sure to use version >= 3.0 of Thymeleaf:

<properties>
  <thymeleaf.version>3.0.3.RELEASE</thymeleaf.version>
  <thymeleaf-layout-dialect.version>2.1.2</thymeleaf-layout-dialect.version>
</properties>
like image 23
yglodt Avatar answered Nov 15 '22 17:11

yglodt