Skip to main content

Sending Stunning HTML Emails in Spring Boot 3.x with Thymeleaf

Sending Stunning HTML Emails in Spring Boot 3.x with Thymeleaf


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

Popular posts from this blog

25+ Spring Data JPA Interview Questions with Answers, Explanations & Use Cases

  ๐Ÿ“˜ Spring Data JPA Interview Questions (with Answers, Explanations & Use Cases) 1. What is JPA and how is it related to Spring Data JPA? Answer: JPA (Java Persistence API) is a Java specification for managing relational data. Spring Data JPA is a part of Spring Data that simplifies JPA usage by reducing boilerplate code. Use Case: Persisting Java objects (like User ) to a relational database without writing SQL. 2. What are the key annotations used in JPA? Answer: @Entity , @Table , @Id , @GeneratedValue , @Column , @ManyToOne , @OneToMany , etc. Explanation: These annotations map Java objects to database tables and relationships. Use Case: Creating a User entity with an auto-generated ID and fields mapped to table columns. 3. What is the difference between JPA and Hibernate? Answer: JPA is a specification; Hibernate is an implementation of that specification. Use Case: Using Hibernate as the default JPA provider in Spring Boot. 4. How do you define a p...

How to Send Emails in Spring Boot Using SMTP (With and Without Attachments)

Sending emails is a common requirement in modern web applications — for things like user registration, password resets, or notifications. In this tutorial, we’ll walk through how to send emails in a Spring Boot application using SMTP , specifically with Gmail’s SMTP server , and demonstrate how to send both plain emails and emails with attachments . ๐Ÿ“บ Video Demo If you prefer watching over reading, here’s a full demo of this tutorial in action: ๐Ÿ“ GitHub Repo  Want the complete working code? Clone the GitHub link provided below which contains all the source code. Source Code GitHub Link: https://github.com/TheDipDeveloper/Spring-Boot-Sending-Email ๐Ÿงฐ Prerequisites Java 17 or above Maven Spring Boot 3.x A Gmail account  ๐Ÿš€ Step 1: Add Spring Boot Mail Dependency First, add all the required dependency on pom.xml file < dependencies > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring...

Create a Real-World Banking System with Spring Boot 3, JPA, MySQL & Postman

Are you looking to build a real-world project using Spring Boot and MySQL? In this tutorial, we'll walk you through creating a complete Banking Service REST API that supports full CRUD operations, money transfers, deposits, and withdrawals. Whether you're preparing for interviews or enhancing your portfolio, this hands-on project will give you practical experience with Spring Boot 3, Spring Data JPA, and RESTful API design. In this post, you'll learn how to build a Banking Service REST API using: ✅ Spring Boot 3.x ✅ Java 17 ✅ MySQL ✅ Postman for API testing ✅ IntelliJ IDEA ✅ GitHub Repo : https://github.com/TheDipDeveloper/Banking-Service-Application-REST-Api By the end, you'll have a complete backend application that supports: Creating bank accounts Fetching account data Deposits and withdrawals Transferring funds between accounts Deleting accounts ๐Ÿ› ️ Tech Stack Java 17 Spring Boot 3.x Spring Data JPA MySQL Lombok ...