Search code examples
htmlspringemailthymeleaf

Spring + thymeleaf html email templates, how to add html tags in messages?


I would like to send html emails from my application, using Thymeleaf engine. I can send html email, the problem comes when i want to bind to the template, let's say

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head></head>
<body>
    <span th:text="${message}"></span>


</body>
</html>

${message} comes from a controller and it's and internationalized message, so i get it in this way

String message = messageSource.getMessage("email_message", null, locale);

And email_message is in my messages_xx.properties files, depending on the locale Is it possibile to add html tags in message?

If i write something like

Hello <b>User</b><br/>Welcome!

in the email i get this message literally, as the tags are not parsed


Solution

  • Try Unescaped Text:

    <span th:utext="${message}"></span>
    

    Note that text->utext change.

    It does not escape html special characters (like <, >, &), that is, it does not turn them to &lt;, '>', '&', so it outputs the text verbatim.

    Please be advised that such a configuration leaves a hole for XSS attack, if the texts you insert do not come from an absolutely trusted source. Of course, if you only want to insert some texts from your properties file that you author yourself, then it is ok.