Steps to Send Email with Thymeleaf template in Spring Boot

Here we created a Spring Boot Project by the help of Spring Initializr. This Initializr can generate the Spring Boot project with required dependencies. Below we explain this project in Step by Step manner for getting more clarity on this article.

Step 1:

Create a Spring Boot project using the Spring Initializr and add the specified Gradle dependencies below:

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}


Main class:

From here, the Spring Application execution is started.

Java
package com.email.template.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class EmailtemplateApplication {

    public static void main(String[] args) {
        SpringApplication.run(EmailtemplateApplication.class, args);
    }

}


Step 2:

  • Now open the application.properties file which is located in resource folder in the Spring Boot project.
  • And write below given configuration properties for configuring the Java mail sender.
  • For java mail configuration, we need below properties. And we can provide our email address and our gmail password.
spring.application.name=emailtemplate

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your_email_address
spring.mail.password=your_email_password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true


Step 3:

Now create one Domain class in the main package of the project folder. And define your own attributes in that domain class based on your requirements. Based on our requirements below we define some fields like to, subject, message, name.

  • The to indicates end user email address.
  • The subject indicates subject of that email you want to send.
  • The message indicates what message you want to send to end user in template.
  • Finally the name indicates end user name.

EmailRequest.java:

Java
package com.email.template.app;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class EmailRequest {
    private String to;
    private String subject;
    private String message;
    private String name;
}


Step 4:

Here we created a Service class by using @Service Annotation with name EmailService.

  • After that we Autowired the Java mail sender and Template Engine.
  • Now we created one method called sendEmail(), This method take to, subject, template, context as input arguments.
  • After this in that method we create a object for MimeMessage for sending Email Template to the end user.
  • After this we define the HTML Context by the help of template engine and set required values to context.

EmailService.java:

Java
package com.email.template.app;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;

@Service
public class EmailService {

    private final JavaMailSender mailSender;
    private final TemplateEngine templateEngine;

    @Autowired
    public EmailService(JavaMailSender mailSender, TemplateEngine templateEngine) {
        this.mailSender = mailSender;
        this.templateEngine = templateEngine;
    }

    public void sendEmail(String to, String subject, String template, Context context) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        // Process the template with the given context
        String htmlContent = templateEngine.process(template, context);

        // Set email properties
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true); // Set true for HTML content

        // Send the email
        mailSender.send(mimeMessage);
    }
}


Step 5:

Once mail business logic is developed in Service class, then we created a RestController by using @RestController annotation with EmailController.

  • After this we autowired the EmailService class for accessing the sendEmail method from that service class.
  • Now, we define a REST API end point by using @PostMapping annotation with method name sendEmail.
  • This method take EmailRequest domain class as input.
  • And we sent required fields names through that domain object and set to Context.

EmailController.java:

Java
package com.email.template.app;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.Context;

@RestController
public class EmailController {

    private final EmailService emailService;

    @Autowired
    public EmailController(EmailService emailService) {
        this.emailService = emailService;
    }

    @PostMapping("/sendEmail")
    public String sendEmail(@RequestBody EmailRequest emailRequest) {
        Context context = new Context();
        // Set variables for the template from the POST request data
        context.setVariable("name", emailRequest.getName());
        context.setVariable("message", emailRequest.getMessage());
        context.setVariable("subject", emailRequest.getSubject());
        try {
            emailService.sendEmail(emailRequest.getTo(), emailRequest.getSubject(), "emailTemplate", context);
            return "Email sent successfully!";
        } catch (Exception e) {
            return "Error sending email: " + e.getMessage();
        }
    }
}


Step 6:

Finally we created a required Email template by using HTML 5 and CSS with the integration of Thymeleaf library in the Spring Boot. In this template we displayed brand name, end user name, subject information, message and other information.

EmailTemplate.html:

HTML
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title th:text="${subject}">Email Template</title>
    <style>
        body {
            font-family: Helvetica, Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f2f2f2;
        }
        .container {
            font-size: 16px;
            width: 70%;
            margin: 50px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .header {
            border-bottom: 1px solid #eee;
            padding-bottom: 20px;
            margin-bottom: 20px;
        }
        .brand {
            font-size: 1.5em;
            color: green !important;
            text-decoration: none;
            font-weight: 800;
        }
        p {
            margin-bottom: 15px;
        }
        .footer {
            color: #aaa;
            font-size: 0.8em;
            font-weight: 300;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <a href="#" class="brand">w3wiki</a>
        </div>
        <h3>Hello, <span th:text="${name}"></span>!</h3>
        <p th:text="${message}"></p>
        <br><br>
        <div class="footer">
            <p>Thank You</p>
            <p>GFG Team.</p>
        </div>
    </div>
</body>
</html>


Step 7:

Once business logic successfully completed, then run this project as Spring Boot App. Here we use Apache tomcat server and this server running on the 8080 port number by default.


Step 8:

Once project is running successfully, now test the API end point by using Post Man tool, by using API end point URL.

We tested this API end point and we got below output. When Email is sent to end user then you got response as Email Sent Successfully!


Output:

When we hit this API endpoint, we will get email like this.




How to Send Email with Thymeleaf Template in Spring Boot?

Spring Boot is a framework for developing web applications. It simplifies development with features like auto-configuration, dependency management, and Spring Security. Thymeleaf, a Java template engine, is easy to use in Spring Boot. It handles XML files and integrates well with the Spring framework. Thymeleaf helps in rendering data to template files. In this article, we will discuss sending emails with Thymeleaf templates in Spring Boot. We’ll use dependencies like Java Mail Sender, Lombok, and Spring Web for this project. Below, we’ll explain the project in detail with Java code.

Prerequisites:

  • Spring Boot
  • Thymeleaf
  • Java Mail Sender
  • Spring Configuration
  • Dependency Management in Spring Boot
  • Lombok
  • Rest APIs
  • Spring MVC pattern

Project Folder Structure:

Below we provide the project folder structure image for reference.



Note: Due to privacy we have removed the personal email address in the java code and in the email template. In java code you can use your own address.

Similar Reads

Steps to Send Email with Thymeleaf template in Spring Boot

Here we created a Spring Boot Project by the help of Spring Initializr. This Initializr can generate the Spring Boot project with required dependencies. Below we explain this project in Step by Step manner for getting more clarity on this article....

Contact Us