How to Send Email with HTML Template in Spring Boot

In the modern world of technology, communication plays a crucial role in our daily lives. Email has remained a reliable and widely used method of communication, both in personal and business contexts. When developing applications, it’s often necessary to integrate email sending functionality. In this tutorial, we’ll explore how to send emails using Spring Boot, a popular framework for building Java applications.

Prerequisites

Before we dive into the implementation, make sure you have the following prerequisites covered:

  1. JDK (Java Development Kit) installed on your system.
  2. A working Spring Boot project.
  3. SMTP Server Details, In this project we are using Gmail SMTP

Note: For this tutorial, we are using our basic skeleton project for springboot. You can also download the project from here.

Step 1: Include Dependencies

Open your pom.xml (for Maven) or build.gradle (for Gradle) and include the necessary dependencies:

For Maven

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

For Gradle:

implementation 'org.springframework.boot:spring-boot-starter-mail'

These dependencies provide the necessary classes and components for email sending in Spring Boot.

Step 2: Configure Email Properties

In the application.properties file of your project (located in the src/main/resources directory), configure the email properties as follows:

# Email Configuration
spring.mail.host=smtp.gmail.com
[email protected]
spring.mail.password=your-email-password
spring.mail.port=587
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

Replace your-smtp-server, [email protected], and your-email-password with the appropriate values for your SMTP server and email account.

Please watch bellow video, to get email smtp details using Gmail.

Gmail SMTP Email settings for Sprin Boot Project

Step 3: Create an Email Service

Within your project, create an email service (EmailService.java) class that will encapsulate the email sending logic. Here’s an example of how it might look:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailService {

    private final JavaMailSender mailSender;

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

    public void sendEmail(String to, String subject, String body) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(body);
        mailSender.send(message);
    }
}

Step 4: Create EmailRequest Class

Create the EmailRequest.java class to represent the details of the email you want to send. This class should have fields for the recipient’s email address, the email subject, and the email body. You can create the EmailRequest class as follows:

public class EmailRequest {
    private String to;
    private String subject;
    private String body;

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }
}

This class acts as a container for the email details, allowing you to easily pass them to the sendEmail method in the EmailService.

Step 5: Sending Emails

With the EmailService and EmailRequest class in place, you can now use them to send emails from your project application. For instance, you could send an email from a controller like bellow, please create EmailController.java Class and paste the below code:

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;

@RestController
public class EmailController {

    private final EmailService emailService;

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

    @PostMapping("/send-email")
    public String sendEmail(@RequestBody EmailRequest emailRequest) {
        emailService.sendEmail(emailRequest.getTo(), emailRequest.getSubject(), emailRequest.getBody());
        return "Email sent successfully!";
    }
}

Step 6: Testing

To test the email sending functionality, run your “myproject” Spring Boot application and use tools like Postman or curl to make a POST request to the /send-email endpoint, providing a JSON payload with the email details.

{
    "to": "[email protected]",
    "subject": "Test Email",
    "body": "This is a test email sent from myproject."
}

For example, using curl:

curl -X POST -H "Content-Type: application/json" -d '{
    "to": "[email protected]",
    "subject": "Test Email",
    "body": "This is a test email sent from myproject."
}' http://localhost:8080/send-email

Send SpringBoot Email with HTML Template

In addition to sending plain text emails, you might want to send emails with visually appealing HTML content. This is particularly useful for newsletters, promotional emails, or any communication that requires rich formatting. Let’s see how you can modify your Spring Boot application to send emails with HTML templates.

Step 1: Update Dependencies

Open your pom.xml (for Maven) or build.gradle (for Gradle) and add the Thymeleaf dependency:

For Maven

<dependency>  
   <groupId>org.springframework.boot</groupId>  
   <artifactId>spring-boot-starter-thymeleaf</artifactId>  
</dependency>  

For Gradle

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

Step 2: Update EmailService

To support sending emails with HTML content, we’ll need to enhance the EmailService class as follows:

package com.example.myproject;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
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 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 body) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(body);
        mailSender.send(message);
    }

    public void sendEmailWithHtmlTemplate(String to, String subject, String templateName, Context context) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8");

        try {
            helper.setTo(to);
            helper.setSubject(subject);
            String htmlContent = templateEngine.process(templateName, context);
            helper.setText(htmlContent, true);
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            // Handle exception
        }
    }
}

Step 3: Create HTML Template

Generate an HTML template named email-template.html within the src/main/resources/templates directory. Leverage Thymeleaf, a templating engine, to include dynamic content:

<!DOCTYPE html>
<html>
<head>
    <title>Email Template</title>
</head>
<body>
    <h1>Greetings from myproject!</h1>
    <p th:text="${message}">Default message</p>
</body>
</html>

Step 4: Update EmailController

Adapt the EmailController to facilitate sending emails with the newly created HTML template:

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("/send-email")
    public String sendEmail(@RequestBody EmailRequest emailRequest) {
        emailService.sendEmail(emailRequest.getTo(), emailRequest.getSubject(), emailRequest.getBody());
        return "Email sent successfully!";
    }

    @PostMapping("/send-html-email")
    public String sendHtmlEmail(@RequestBody EmailRequest emailRequest) {
        Context context = new Context();
        context.setVariable("message", emailRequest.getBody());

        emailService.sendEmailWithHtmlTemplate(emailRequest.getTo(), emailRequest.getSubject(), "email-template", context);
        return "HTML email sent successfully!";
    }
}

Step 5: Testing HTML Email

To validate the HTML email feature, employ tools such as Postman or curl to execute a POST request to the /send-html-email endpoint, while providing a JSON payload:

{
    "to": "[email protected]",
    "subject": "Test HTML Email",
    "body": "This is an <b>HTML</b> email sent from myproject."
}

For example, using curl:

curl -X POST -H "Content-Type: application/json" -d '{
    "to": "[email protected]",
    "subject": "Test HTML Email",
    "body": "This is an <b>HTML</b> email sent from myproject."
}' http://localhost:8080/send-html-email

Conclusion

Integrating email sending functionality into your SpringBoot application can enhance its communication capabilities and provide valuable notifications to users. By following this step-by-step guide, you’ve learned how to set up the necessary dependencies, configure email properties, create an email service, and send emails. With this knowledge, you can now incorporate email sending into your Spring Boot projects with ease.

Find this project on Github.

Whats Next: How to Send Email with File Attachment in Spring Boot: PDF, Image

Blogs You Might Like to Read!