Home Spring Boot Spring boot email template with Thymeleaf

Spring boot email template with Thymeleaf

In this tutorial we demonstrate how to send a mail with attachment using spring boot email template example, it uses Spring boot, Thymeleaf and HTML, gmail SMTP. we have used Gmail SMTP settings to send an email using this demo application.

1. What is Thymeleaf

 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.

2. Spring boot email template with Thymeleaf Demo app

2.1. 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

2.2 Project Structure:

spring boot email template

2.3. 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 dependencies.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
		<relativePath/> <!-- lookup parent from repository -->
	<description>Demo project for Spring Boot Email Tempalte with Thymeleaf</description>





2.4. 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

application.yml :

# application.yml

    default-encoding: UTF-8
    host: smtp.gmail.com
    username: [email protected]
    password: youremailpassword
    port: 587
          auth: true
            enable: true
    protocol: smtp
    test-connection: false

application.properties :

[email protected]

2.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.

public class ThymeleafTemplateConfig {

    public SpringTemplateEngine springTemplateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        return templateEngine;

    public SpringResourceTemplateResolver htmlTemplateResolver(){
        SpringResourceTemplateResolver emailTemplateResolver = new SpringResourceTemplateResolver();
        return emailTemplateResolver;

2.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, etc.
  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.

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.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml">
    <title>Spring boot eamil teplate with Thymeleaf</title>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

    <link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'/>

    <!-- use the font -->
        body {
            font-family: 'Roboto', sans-serif;
            font-size: 48px;
    <p th:text="${'Hello Dear ' + name}"></p>

    <p th:if="${name.length() > 5}">
      Wow! You've got a long name (more than 5 chars)!
      You have been successfully subscribed to the <b>Fake newsletter</b> on
      <span th:text="${#dates.format(#dates.createNow(), 'dd MMM yyyy HH:mm')}"></span>
      You can find <b>your inlined image</b> just below this text.
     <a href="https://javabydeveloper.com">
        <img src="http://javabydeveloper.com/wp-content/uploads/2019/12/javabydeveloper-email.png" alt="htts://javabydeveloper.com" height="110" width="500"/>
      Regards, <br />
      <em th:text="${sign}"></em>
      <p th:text="${location}"></p>

2.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.

public class EmailSenderService {

    private JavaMailSender emailSender;

    private SpringTemplateEngine templateEngine;

    public void sendEmail(Mail mail) throws MessagingException, IOException {
        MimeMessage message = emailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,

        helper.addAttachment("template-cover.png", new ClassPathResource("javabydeveloper-email.PNG"));

        Context context = new Context();
        String html = templateEngine.process("newsletter-template", context);

        helper.setText(html, true);



2.8. Email with CSS Styles and Inline image attachments

There might be two cases where image files available, either you keep them in application itself or external location (for example, an image server or in AWS S3 bucket or other cloud platforms or from public server).

Embedding Image in email template from your application local resource:

// in your EmailSenderService, add resource file to attachment
helper.addAttachment("template-cover.png", new ClassPathResource("javabydeveloper-email.PNG"));

// in your template embed using cid (content-id)
<img src="cid:attachment.png" />

Embedding Image in email template from external resource:

<!-- Embed using direct url like following example-->
<img src="https://externalsite.com/../../logo.png" alt="htts://javabydeveloper.com" height="110" width="500"/>

You can use external css resources and inline css as well within your template directly.

    <link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'/>
    <!-- use the font -->
        body {
            font-family: 'Roboto', sans-serif;
            font-size: 48px;

For more details about email embedded attachments you checkout at git source.

3. Send email Demo

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

public class SpringBootEmailTemplateApplication implements ApplicationRunner{
    private EmailSenderService emailService;
	private static Logger log = LoggerFactory.getLogger(SpringBootEmailTemplateApplication.class); 
	public static void main(String[] args) {
		SpringApplication.run(SpringBootEmailTemplateApplication.class, args);

	public void run(ApplicationArguments args) throws Exception {
		log.info("START... Sending email");

        Mail mail = new Mail();
        mail.setFrom("[email protected]");//replace with your desired email
        mail.setMailTo("[email protected]");//replace with your desired email
        mail.setSubject("Email with Spring boot and thymeleaf template!");

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("name", "Developer!");
        model.put("location", "United States");
        model.put("sign", "Java Developer");

        log.info("END... Email sent success");

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

received spring boot email

4. Download source code

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

You also might be interested in following tutorials:

  1. Spring @Autowired
  2. Spring @Lazy
  3. Spring Boot XML Configuration
  4. Spring Injecting Collection
  5. Spring @Primary
  6. Spring @Import
  7. Spring Component Scanning
  8. Spring @ComponentScan Filter Types
  9. Spring @Order

5. References

  1. Sending email in Spring with Thymeleaf
  2. Javamail not working with gmail SMTP
  3. A github reference on embed html image


Please enter your comment!
Please enter your name here