How to Send Email with Thymeleaf Template in Spring Boot?
Last Updated :
20 May, 2024
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.
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">GeeksForGeeks</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.

Similar Reads
How to Call REST Services with WebClient in Spring Boot?
Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring WebClient is a non-blocking and reactive web client
11 min read
Spring Boot - How Thymeleaf Works?
Thymeleaf is a Java library, and template engine used to parse and render the data produced by the application to template files - thus providing transformation. It is just like HTML but is provided with more attributes for working with rendered data. It allows caching of the parsed data/file to inc
4 min read
Email Templates with Jinja in Python
HTML emails play a crucial role in modern communication, whether for newsletters, notifications, or transactional emails. Jinja, a powerful templating engine for Python, offers flexibility for creating dynamic and visually appealing HTML email templates. In this article, we will see how we can use J
3 min read
How to Change the Default Port in Spring Boot?
Spring Boot framework provides a default embedded server i.e. the Tomcat server for many configuration properties to run the Spring Boot application. The application runs on the default port which is 8080. As per the application need, we can also change this default port for the embedded server. In
4 min read
Spring MVC â Integrate with Thymeleaf for Server-Side Rendering
In modern web development, server-side rendering is crucial for creating fast, SEO-friendly, dynamic web pages. By integrating Spring MVC with Thymeleaf, developers can build powerful and flexible solutions for rendering HTML content on the server side. Thymeleaf, a natural templating engine, works
6 min read
How to Create and Setup Spring Boot Project in Spring Tool Suite?
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
3 min read
Spring Boot - Rest Template
RestTemplate is a powerful synchronous client for handling HTTP communication in Spring Boot applications. It internally uses an HTTP client library i.e. java.net.HttpURLConnection, simplifying the process of making RESTful requests to external services and APIs, including convenience, along with in
7 min read
Spring Boot - Sending SMS with Twilio
Spring is a widely used framework of Java that allows us to create stand-alone and robust applications at the enterprise level. Spring boot is a tool or an extension of the Spring framework that makes developing web applications and microservices much faster and easier. It offers an integrated serve
6 min read
How to Configure Spring Boot TestRestTemplate?
The Spring Framework is an open-source framework for creating applications, providing many annotations and features to make development easier. Spring Boot simplifies the setup and development of the Spring applications. One useful utility for testing RESTful web services in Spring Boot is TestRestT
4 min read
How to Generate Spring Boot REST Client with Swagger?
Spring Boot is a powerful framework for building Java applications, particularly RESTful web services. When developing the REST APIs, it can be crucial to provide documentation that is both user-friendly and interactive. Swagger is an open-source that simplifies this by generating the API documentat
6 min read