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">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.javabydeveloper</groupId>
	<artifactId>SpringBootEmailTemplate</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootEmailTemplate</name>
	<description>Demo project for Spring Boot Email Tempalte with Thymeleaf</description>

	<properties>
		<java.version>1.8</java.version>
		<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
	</properties>

	<dependencies>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
		
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>nz.net.ultraq.thymeleaf</groupId>
            <artifactId>thymeleaf-layout-dialect</artifactId>
        </dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

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

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

application.properties :

spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.gmail.com
[email protected]
spring.mail.password=yourgmailpassword
spring.mail.port=587
spring.mail.protocol=smtp
spring.mail.test-connection=false
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

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.

@Configuration
public class ThymeleafTemplateConfig {

    @Bean
    public SpringTemplateEngine springTemplateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.addTemplateResolver(htmlTemplateResolver());
        return templateEngine;
    }

    @Bean
    public SpringResourceTemplateResolver htmlTemplateResolver(){
        SpringResourceTemplateResolver emailTemplateResolver = new SpringResourceTemplateResolver();
        emailTemplateResolver.setPrefix("/templates/");
        emailTemplateResolver.setSuffix(".html");
        emailTemplateResolver.setTemplateMode(TemplateMode.HTML);
        emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
        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">
<head>
    <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 -->
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            font-size: 48px;
        }
    </style>
</head>
 <body>
    <p th:text="${'Hello Dear ' + name}"></p>

    <p th:if="${name.length() > 5}">
      Wow! You've got a long name (more than 5 chars)!
    </p>
    <p>
      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>
    </p>
    
    <p>
      You can find <b>your inlined image</b> just below this text.
    </p>
    <p>
    
     <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"/>
      </a>
    </p>
    <p>
      Regards, <br />
      <em th:text="${sign}"></em>
      <p th:text="${location}"></p>
    </p>
  </body>
</html>

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.

@Service
public class EmailSenderService {

    @Autowired
    private JavaMailSender emailSender;

    @Autowired
    private SpringTemplateEngine templateEngine;


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

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

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

        helper.setTo(mail.getMailTo());
        helper.setText(html, true);
        helper.setSubject(mail.getSubject());
        helper.setFrom(mail.getFrom());

        emailSender.send(message);
    }

}

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.

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

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.

@SpringBootApplication
@ComponentScan("com.javabydeveloper.mail.service")
public class SpringBootEmailTemplateApplication implements ApplicationRunner{
	
	@Autowired
    private EmailSenderService emailService;
	
	private static Logger log = LoggerFactory.getLogger(SpringBootEmailTemplateApplication.class); 
	
	public static void main(String[] args) {
		SpringApplication.run(SpringBootEmailTemplateApplication.class, args);
	}

	@Override
	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");
        mail.setProps(model);

        emailService.sendEmail(mail);
        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

Download source code

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

References

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

Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Follow him on LinkedIn or Twitter or Facebook

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Categories