Sending emails using Spring mail and Spring boot

Java featured image

1. Overview

Sending emails is quite a frequent and common task in Java EE projects.

In this article, I will show you how to send emails using Spring mail in a Spring boot application.

2. Implementation

1. Create a new Spring boot project using Spring initializr, then add the spring-boot-starter-mail dependency to your pom.xml.


2. Add the following config properties to your


For this example, I used the Gmail SMTP server settings, but you can use any SMTP server you want.

3. Create two Java POJOs and to hold mail’s detail.

  • : we will use it to send a simple text mail.
  • :  we will use it to send an HTML mail.
public class SimpleMail {

    private final String to;

    public SimpleMail(String to) { = to;

    public String getTo() {

    public String getSubject() {
        return "Simple Email Subject";

    public String getContent() {
        return "Hello client,\n This a simple email content !";
public class HTMLMail {

    private final String to;

    public HTMLMail(String to) { = to;

    public String getTo() {

    public String getSubject() {
        return "HTML Email Subject";

    public String getContent() {
        return "<html>" +
                    "<body>" +
                        "<p>Hello client,</p>" +
                        "<p>This an <strong>HTML</strong> email content !</p>" +
                    "</body>" +

4. We will take advantage of the, to send simple text and HTML emails.

public class MailSenderService {

    private JavaMailSender mailSender;

    // Use it to send Simple text emails
    public void sendSimpleMail(SimpleMail mail) {

        SimpleMailMessage message = new SimpleMailMessage();



    // Use it to send HTML emails
    public void sendHTMLMail(HTMLMail mail) throws MessagingException {

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, false, "utf-8");

        message.setContent(mail.getContent(), "text/html");


5. Use the created service to send emails via sendSimpleMail(mail) or sendHTMLMail(mail).

public class SendEmailsSpringBootExampleApplication implements CommandLineRunner {

    private MailSenderService senderService;

	public void run(String... args) throws Exception {

	    // send a simple mail
        senderService.sendSimpleMail(new SimpleMail(""));

        //send an HTML mail
        senderService.sendHTMLMail(new HTMLMail(""));

    // ...

6. After executing the application, two different emails will be sent to, simple text email and HTML email.

Spring Mail with Spring Boot simple email

Spring Mail with Spring Boot HTML email

Find the source code of this example on GitHub.


Leave a Reply


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Notify of