Sending HTML Emails with Thymeleaf in Spring applications
Thymeleaf is a modern server-side Java template engine for both web and standalone environments.
Overview
We need to prepare html templates to be sent in the email as the content and use Thymeleaf to generate our content from template. Thymeleaf has variable expression support as ${variable}
so the following HTML can be rendered dynamically with supplying the variables.
<!DOCTYPE html>
<html>
<head>
<title>Email Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="#{user.name}">Default body!</p>
</body>
</html>
So if we look at the variable part:
<p th:text="#{user.name}">Default body!</p>
The th:text
attribute, evaluates the value of the variable which is user.name
and the value will be placed inside the body of the tag. So it will be rendered as
<p>{{user.name}}</p>
If the user.name variable is not set, then the default body which is Default body!
in our example will be used as the content of the <p>
tag.
So how we set these variables?
Configuring Thymeleaf
We can start with adding the dependency:
Thymeleaf expects all the HTML templates to be placed under resources/templates
folder. So we can design the HTML file that we want to send in the mail as a view and put it under this folder.
If you are lazy or not very good at CSS no worries a fast way to generate fancy HTML mail content might be using some ready templates, or designing with tools such as:
For instance Sendgrid has a very handy template design tool that you can export the HTML code after designing.
Bare in mind that once your HTML code is ready, if you want to render dynamic content in it, you should add th:text
attributes and the variable name to the tag as explained above.
And then we will create MailContentBuilder which will use the template engine to process our template with given parameters.
Template engine uses the given file name mailTemplate.html
and processes it with the given context. Here the context object is an instance of Thymeleaf context and it used to store our parameters. So our variables in the HTML will be filled from these context.
Configuring Java Mail Sender
First we need to add the dependency for JavaMailSender
We also need to configure our mail server to be able to send the mails. We can choose Gmail, Mailgun or any other mail server.
We can send SimpleMailMessage
or MimeMessage
by JavaMailSender.
SimpleMailMessage models a simple mail message, including data such as the from, to, cc, subject, and text fields.
So for creating more sophisticated messages, for example messages with attachments, special character encodings, or html content we should use MimeMessage
We can use both methods to send emails but when we plan to send HTML content we can simply call use sendComplexMail
: