- Spring boot email template with Thymeleaf
In this tutorial we demonstrate how to send a spring boot email template using Thymeleaf and HTML, SMTP with an attachment. Thymeleaf is a modern server-side Java template engine for both web and standalone environments. HTML templates written in Thymeleaf still look and work like HTML.
Technologies used :
- Spring Boot 2.2.2.RELEASE
- Spring 5.2.2.RELEASE
- Thymeleaf 3.0.11.RELEASE
- Java Mail 1.6.4
- Maven 3
- Java 8
- Spring Tool Suite 3.9.8.RELEASE
To send email, declare
thymeleaf-layout-dialect dependencies in pom.xml, they will pull all the JavaMail, Thymeleaf and dependencies.
3. Email Configuration Properties
We can use two types of configuration files to configure email SMTP settings proprties, either one we can use.
4. Create Mail class
5. Spring Thymeleaf configuration
In order to process our templates, we will configure a
SpringTemplateEngine especially configured for email processing, in our Spring boot email template configuration. We need to tell Thymeleaf where the email templates are located. We do this by creating and configuring the
SpringResourceTemplateResolver. We can set a prefix and suffix to configure where Thymeleaf will search for the HTML email templates.
6. Thymeleaf HTML email template
Using Thymeleaf for processing our email templates would allow us to use some interesting features:
- Expressions in Spring EL.
- Flow control: iterations, conditionals, …
- Utility functions: date/number formatting, dealing with lists, arrays…
- Easy i18n, integrated with our application’s Spring internationalization infrastructure.
- Natural templating: our email templates can be static prototypes, written by UI designers.
Also, given the fact that Thymeleaf has no required dependencies on the servlet API, there would be no need at all to create or send email from a web application. In this example we are going create very simple HTML template.
7. Create EmailSenderService to send emails
We can set the properties to
Context object which holds key value pairs, we process the HTML Thymeleaf Email Template by calling the
SpringTemplateEngine.process() method and passing a
Context object, and then key value pairs can be used in html template using EL.
Start Spring Boot, and it will send out a mail to the recipient.
You will receive an email like below, an image attached to email and inline as well.