HomeSpring BootSpring 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="" xmlns:xsi=""
		<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

application.yml :

# application.yml

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

[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" "">
<html xmlns:th="" xmlns="">
    <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='' 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="">
        <img src="" alt="htts://" 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="" alt="htts://" height="110" width="500"/>

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

    <link href='' 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) {, args);

	public void run(ApplicationArguments args) throws Exception {"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");

        emailService.sendEmail(mail);"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. Free template with Inline CSS

Following is the another example with responsive transactional in-lined CSS Thymeleaf template. You can get this template from github in HTML.

Sending email code.

    private void sendInlinedCssEmail(Mail mail) throws MessagingException, IOException {"START...Sending Inlined CSS Email");

        mail.setSubject("Email with Inlined CSS Responsive Thymeleaf Template!");

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("name", "Peter Milanovich!");
        model.put("address", "Company Inc, 3 Abbey Road, San Francisco CA 94102");
        model.put("sign", "JavaByDeveloper");
        model.put("type", "TRANSACTIONAL");

        emailService.sendEmail(mail);"END... Sending Inlined CSS Email");

Received email demo.

thymeleaf email
Responsive Inlined CSS Thymeleaf Template

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