In this guide, we'll walk you through how to send dynamic and responsive HTML emails using Spring Boot and the Thymeleaf template engine. By the end, you’ll have a fully functional system that sends personalized emails right from your Java backend.
๐ GitHub Reference
You can explore a complete working example on GitHub here:
๐ Html-Email-Spring-Boot by TheDipDeveloper
๐ Project Setup: What You’ll Need
Start by creating a Spring Boot project with these dependencies:
-
Spring Web
-
Spring Boot Starter Mail
-
Thymeleaf
Lombok
Add These to pom.xml
:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
⚙️ Configure Your SMTP Settings
In application.properties
, set up your email credentials. Here's an example using Gmail:
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=emailId
spring.mail.password=16DigitAppPasswordWithOutSpace
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
⚠️ Tip: For Gmail, enable "App Passwords" if you use two-factor authentication.
๐จ Design the Email Template with Thymeleaf
Create a file named EmailTemplate.html
in src/main/resources/templates/
:
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<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">Dip Developer</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>Dip Developer Team.</p>
</div>
</div>
</body>
</html>
Use ${name},
${message}, ${subject} to inject dynamic values when sending the email.
๐ง Write the Email Sending Service
package com.dipdeveloper.spring_html_email;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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;
@Service
public class EmailServiceImpl implements EmailService {
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private TemplateEngine templateEngine;
@Value("${spring.mail.username}")
private String sender;
@Override
public void sendEmailWithHtml(String to, String subject, String template, Context context) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
String htmlContent = templateEngine.process(template, context);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlContent, true);
javaMailSender.send(mimeMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
๐งช Test with a Simple Controller
package com.dipdeveloper.spring_html_email;
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 {
@Autowired
private EmailServiceImpl emailServiceImpl;
@PostMapping("/sendMailWithHtml")
public String sendMailWithHtml(@RequestBody EmailDetails emailDetails) {
Context context = new Context();
context.setVariable("name", emailDetails.getName());
context.setVariable("message", emailDetails.getMessage());
context.setVariable("subject", emailDetails.getSubject());
try {
emailServiceImpl.sendEmailWithHtml(emailDetails.getTo(),
emailDetails.getSubject(),
"EmailTemplate",
context);
return "Email sent successfully with HTML template.";
} catch (Exception e) {
return "Error sending email: " + e.getMessage();
}
}
}
๐งช Test Using curl
curl --location 'http://localhost:8080/sendMailWithHtml' \
--header 'Content-Type: application/json' \
--data-raw '{
"to": "test@gmail.com",
"subject": "Message with HTML template",
"message": "Welcome to our YouTube Channel! Please SUBSCRIBE",
"name": "Viewers"
}'
✅ Conclusion
Integrating Thymeleaf with Spring Boot's mail support makes it easy to send dynamic, professional-looking emails. With a reusable template and structured service logic, your app can handle email notifications in a clean and maintainable way.
Let us know in the comments if you’d like to see advanced use cases like attachments, inline images, or multi-language templates!
Comments
Post a Comment