1. 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 :

  1. Spring Boot 2.2.2.RELEASE
  2. Spring 5.2.2.RELEASE
  3. Thymeleaf 3.0.11.RELEASE
  4. Java Mail 1.6.4
  5. Maven 3
  6. Java 8
  7. Spring Tool Suite 3.9.8.RELEASE

1.Project Directory:

spring boot email template

2. Project Dependencies:

To send email, declare spring-boot-starter-mail,  thymeleaf-spring5,  thymeleaf-layout-dialect  dependencies in pom.xml, they will pull all the JavaMail, Thymeleaf and dependencies.

Copy to Clipboard

3. Email Configuration Properties

We can use two types of configuration files to configure email SMTP settings proprties, either one we can use.

  1.  application.yml
  2.  application.properties


Copy to Clipboard


Copy to Clipboard

4. Create Mail class

Copy to Clipboard

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.

Copy to Clipboard

6. Thymeleaf HTML email template

Using Thymeleaf for processing our email templates would allow us to use some interesting features:

  1. Expressions in Spring EL.
  2. Flow control: iterationsconditionals, …
  3. Utility functions: date/number formatting, dealing with lists, arrays…
  4. Easy i18n, integrated with our application’s Spring internationalization infrastructure.
  5. Natural templating: our email templates can be static prototypes, written by UI designers.
  6. etc…

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.

Copy to Clipboard

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.

Copy to Clipboard

8. Demo

Start Spring Boot, and it will send out a mail to the recipient.

Copy to Clipboard

You will receive an email like below, an image attached to email and inline as well.

received spring boot email

Download source code

Download SpringbootEmailTemplate example from our Github.
Spring boot email template source code at Github