Date:

Share:

Send Email with Thymeleaf template in Spring Boot

Related Articles

In this article, we will learn how to connect emails using the Thymeleaf template and send emails using Spring Framework’s JavaMailSender.

Overview

thyme Is a modern versatile Java template engine. Thymeleaf is mainly used to build elegant HTML templates. Spring boot web MVC provides good integration with Thymeleaf for server-side server development.

We will first use Thymeleaf templates to compose HTML emails and then we will use Spring Framework’s JavaMailSender to send emails.

Project definition

For initial setup of your Spring Boot project, you must use Spring Initializr. Select the Sends Java Mail and thyme As a dependency.

You can use the Maven or Gradle construction tools of your choice: –

Project Maven

Click the link below to create a Maven project with a pre-selected required dependency: –
https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.6.1&packaging=jar&jvmVersion=11&groupId=com.example&artifactId=email&name=email&description=Send%20Email%20withates%20Thym , thymeleaf

pom.xml
<!-- to send email using java Mail and spring framework's JavaMailSender -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<!-- to create email templates using Thymeleaf server-side Java template engine -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<!-- to write test class using junit jupiter -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

Gardel Project

Click the link below to create a Gradle project with a pre-selected required dependency: –

https://start.spring.io/#!type=gradle-project&language=java&platformVersion=2.6.1&packaging=jar&jvmVersion=11&groupId=com.example&artifactId=email&name=email&description=Send%20Email%20with%20Tmailel & mailTeamel , thymeleaf

build.gradle
dependencies 
  // to send email using java Mail and spring framework's JavaMailSender
  implementation 'org.springframework.boot:spring-boot-starter-mail'

  // to create email templates using Thymeleaf server-side Java template engine
  implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

  // to write test class using junit jupiter
  testImplementation 'org.springframework.boot:spring-boot-starter-test'

Project structure

A typical e-mail service writing project structure looks like this:

📖springboot-email
  📁src
    📁main
      📁java
        📦com.example.email 
          📦config 
            📄ThymeleafTemplateConfig 
          📦model 
            📄Email
          📦service 
            📄EmailSenderService
          EmailApplication
      📁resources
        📁templates 
          📄welcome-email.htmlapplication.yml
  pom.xml
  build.gradle

Thymeleaf email template configuration

In order to process our email templates, we will define a SpringTemplateEngine: –

package com.example.email.config;

@Configuration
public class ThymeleafTemplateConfig 

    @Bean
    public SpringTemplateEngine springTemplateEngine() 
        SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
        springTemplateEngine.addTemplateResolver(emailTemplateResolver());
        return springTemplateEngine;
    

    public ClassLoaderTemplateResolver emailTemplateResolver() 
        ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
        emailTemplateResolver.setPrefix("/templates/");
        emailTemplateResolver.setSuffix(".html");
        emailTemplateResolver.setTemplateMode(TemplateMode.HTML);
        emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
        emailTemplateResolver.setCacheable(false);
        return emailTemplateResolver;
    

This template configuration will look for templates in src/main/resources/templates/ Folder with .html ending.

Let’s create the HTML template of our welcome email with Thymeleaf: –

src / main / resources / templates / welcome-email.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title th:remove="all">Template for HTML email with inline image</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    </head>
    <body>
        <p>
            Hello, <span th:text="$name">Peter Static</span>!
        </p>
        <p th:if="$name.length() > 10">
            Wow! You've got a long name (more than 10 chars)!
        </p>
        <p>
            You have been successfully subscribed to the <b>CodingNConcepts</b> on
            <span th:text="$subscriptionDate">28-12-2012</span>
        </p>
        <p>We write on following technologies:-</p>
        <ul th:remove="all-but-first">
            <li th:each="tech : $technologies" th:text="$tech">Java</li>
            <li>JavaScript</li>
            <li>CSS</li>
        </ul>
        <p>
            Regards, <br/>
            <em>The CodingNConcepts Team</em>
        </p>
    </body>
</html>

JavaMailSender configuration

Provide the SMTP (mail) server configuration in application.yml or application.properties File to boot JavaMailSender, Which we will use to send emails.

application.yml
spring:
  mail:
    default-encoding: UTF-8
    host: smtp.gmail.com
    port: 587
    username: lahoti.ashish20@gmail.com
    password: #gmail_app_password    
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
        debug: true
    protocol: smtp
    test-connection: false

Some popular SMTP server specifications are as follows:

If you want to use Gmail or Yahoo server to send email then you need valid Username and password For verification. You can use your existing email address for example lahoti.ashish20@gmail.com As a username but the password is not the same as your email password. You must create an app password from your mail account for use with an SMTP (mail) server.

If you work in an organization, you may need your organization’s SMTP server information to configure.

E-mail sending service

Let’s use SpringTemplateEngine To write email and JavaMailSender Send an email to our service department: –

package com.example.email.service;

@Service
@RequiredArgsConstructor
@Slf4j
public class EmailSenderService 

    private final JavaMailSender emailSender;
    private final SpringTemplateEngine templateEngine;

    public void sendHtmlMessage(Email email) throws MessagingException 
        MimeMessage message = emailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED, StandardCharsets.UTF_8.name());
        Context context = new Context();
        context.setVariables(email.getProperties());
        helper.setFrom(email.getFrom());
        helper.setTo(email.getTo());
        helper.setSubject(email.getSubject());
        String html = templateEngine.process(email.getTemplate(), context);
        helper.setText(html, true);

        log.info("Sending email:  with html body: ", email, html);
        emailSender.send(message);
    

Checking Email Service

Now it’s time to dump her and move on welcome-email.html Thyme pattern

@SpringBootTest
public class EmailSenderServiceTest 

    @Autowired
    private EmailSenderService emailSenderService;

    @Test
    public void sendHtmlMessageTest() throws MessagingException 
        Email email = new Email();
        email.setTo("lahoti.ashish20@gmail.com");
        email.setFrom("lahoti.ashish20@gmail.com");
        email.setSubject("Welcome Email from CodingNConcepts");
        email.setTemplate("welcome-email.html");
        Map<String, Object> properties = new HashMap<>();
        properties.put("name", "Ashish");
        properties.put("subscriptionDate", LocalDate.now().toString());
        properties.put("technologies", Arrays.asList("Python", "Go", "C#"));
        email.setProperties(properties);

        Assertions.assertDoesNotThrow(() -> emailSenderService.sendHtmlMessage(email));
    

Wow! A message arrived in my mailbox: –

Download the full source code for the examples in this post from github / springboot-email

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles