Spring Boot – Sending Email via SMTP
Last Updated :
12 Apr, 2025
Spring Boot provides the ability to send emails via SMTP using the JavaMail Library. Here we will be illustrating step-by-step guidelines to develop Restful web services that can be used to send emails with or without attachments. In order to begin with the steps, let us first create a Spring Boot project using Spring Initializer.
Implementation:
Step 1: Adding the spring-boot-starter-mail dependency in pom.xml.
XML
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
This dependency is a starter for using JavaMail and can be considered as Spring Framework’s email sending support
Step 2: Setting up Application.properties file with configurations required for using Gmail SMTP server.
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<Login User to SMTP server>
spring.mail.password=<Login password to SMTP server>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
The Gmail Id used to login into your Gmail account can be provided as the username. For password generation, 2-step verification needs to be enabled for your account as follows:

Following that, AppPassword needs to be created using the following path:
Login to Gmail
-> Manage your Google Account
-> Security
-> App Passwords
-> Provide your login password
-> Select app with a custom name
-> Click on Generate

Note: For reference,
If you don’t find the App Password option under Security even after enabling 2-step verification, you might be encountering an issue detailed in this Google Support Thread on App Passwords.
To generate an App Password, visit the Google App Passwords page. This page will guide you through the process of creating an App Password for your Gmail account.
Step 3: Creating EmailDetails class that contains fields such as recipient, msgBody, subject, and attachment.
Java
// Java Program to Illustrate EmailDetails Class
package com.SpringBootEmail.Entity;
// Importing required classes
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
// Annotations
@Data
@AllArgsConstructor
@NoArgsConstructor
// Class
public class EmailDetails {
// Class data members
private String recipient;
private String msgBody;
private String subject;
private String attachment;
}
Step 4: Creating interface EmailService and implementing class EmailServiceImpl of service layer.
The EmailService interface defines two methods:
- String sendSimpleMail(EmailDetails details): This method can be used to send a simple text email to the desired recipient.
- String sendMailWithAttachment(EmailDetails details): This method can be used to send an email along with an attachment to the desired recipient.
The Interface and service implementation class is as shown below in example as follows:
File: EmailService.java
Java
// Java Program to Illustrate Creation Of
// Service Interface
package com.SpringBootEmail.service;
// Importing required classes
import com.SpringBootEmail.Entity.EmailDetails;
// Interface
public interface EmailService {
// Method
// To send a simple email
String sendSimpleMail(EmailDetails details);
// Method
// To send an email with attachment
String sendMailWithAttachment(EmailDetails details);
}
JavaMailSender interface of JavaMail API is used here to send simple text email.
To send a more sophisticated email with an attachment, MimeMessage can be used. MimeMessageHelper works as a helper class for MimeMessage to add the attachment and other details required to send the mail.
File: EmailServiceImpl.java
Java
// Java Program to Illustrate Creation Of
// Service implementation class
package com.SpringBootEmail.service;
// Importing required classes
import com.SpringBootEmail.Entity.EmailDetails;
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
// Annotation
@Service
// Class
// Implementing EmailService interface
public class EmailServiceImpl implements EmailService {
@Autowired private JavaMailSender javaMailSender;
@Value("${spring.mail.username}") private String sender;
// Method 1
// To send a simple email
public String sendSimpleMail(EmailDetails details)
{
// Try block to check for exceptions
try {
// Creating a simple mail message
SimpleMailMessage mailMessage
= new SimpleMailMessage();
// Setting up necessary details
mailMessage.setFrom(sender);
mailMessage.setTo(details.getRecipient());
mailMessage.setText(details.getMsgBody());
mailMessage.setSubject(details.getSubject());
// Sending the mail
javaMailSender.send(mailMessage);
return "Mail Sent Successfully...";
}
// Catch block to handle the exceptions
catch (Exception e) {
return "Error while Sending Mail";
}
}
// Method 2
// To send an email with attachment
public String
sendMailWithAttachment(EmailDetails details)
{
// Creating a mime message
MimeMessage mimeMessage
= javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper;
try {
// Setting multipart as true for attachments to
// be send
mimeMessageHelper
= new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(sender);
mimeMessageHelper.setTo(details.getRecipient());
mimeMessageHelper.setText(details.getMsgBody());
mimeMessageHelper.setSubject(
details.getSubject());
// Adding the attachment
FileSystemResource file
= new FileSystemResource(
new File(details.getAttachment()));
mimeMessageHelper.addAttachment(
file.getFilename(), file);
// Sending the mail
javaMailSender.send(mimeMessage);
return "Mail sent Successfully";
}
// Catch block to handle MessagingException
catch (MessagingException e) {
// Display message when exception occurred
return "Error while sending mail!!!";
}
}
}
Step 5: Creating a Rest Controller EmailController which defines various API for sending email.
Java
// Java Program to Create Rest Controller that
// Defines various API for Sending Mail
package com.SpringBootEmail.controller;
// Importing required classes
import com.SpringBootEmail.Entity.EmailDetails;
import com.SpringBootEmail.service.EmailService;
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;
// Annotation
@RestController
// Class
public class EmailController {
@Autowired private EmailService emailService;
// Sending a simple Email
@PostMapping("/sendMail")
public String
sendMail(@RequestBody EmailDetails details)
{
String status
= emailService.sendSimpleMail(details);
return status;
}
// Sending email with attachment
@PostMapping("/sendMailWithAttachment")
public String sendMailWithAttachment(
@RequestBody EmailDetails details)
{
String status
= emailService.sendMailWithAttachment(details);
return status;
}
}
Step 6: Running the Spring Boot Application and hitting http://localhost:8080/sendMail to send a simple email

Mail received on Gmail is as follows:

Step 7: Running the Spring Boot Application and hitting http://localhost:8080/sendMailWithAttachment to send an email along with an attachment.

Mail received on Gmail is as follows:

Similar Reads
Spring Boot - Introduction to RESTful Web Services
RESTful Web Services REST stands for REpresentational State Transfer. It was developed by Roy Thomas Fielding, one of the principal authors of the web protocol HTTP. Consequently, REST was an architectural approach designed to make the optimum use of the HTTP protocol. It uses the concepts and verbs
5 min read
How to create a basic application in Java Spring Boot
Spring Boot is the most popular Java framework that is used for developing RESTful web applications. In this article, we will see how to create a basic Spring Boot application.Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also p
3 min read
How to Create a REST API using Java Spring Boot?
Representational State Transfer (REST) is a software architectural style that defines a set of constraints for creating web services. RESTful web services allow systems to access and manipulate web resources through a uniform and predefined set of stateless operations. Unlike SOAP, which exposes its
4 min read
Easiest Way to Create REST API using Spring Boot
Spring Boot is a powerful framework that makes it easy to create RESTful APIs. Creating a REST API using Spring Boot is one of the fastest and simplest ways to develop scalable and production-ready web services. Spring Boot simplifies REST API development by providing built-in features such as autom
11 min read
Java Spring Boot Microservices Sample Project
Microservices are more popular nowadays. They can be written in any language. In this article, let us see Spring Boot Microservices. in this article let us see a base project "currency-exchange-sample-service" which has a business logic and which can be invoked in another project "currency-conversio
9 min read
Difference between Spring MVC and Spring Boot
1. Spring MVC : Spring is widely used for creating scalable applications. For web applications Spring provides Spring MVC framework which is a widely used module of spring which is used to create scalable web applications. Spring MVC framework enables the separation of modules namely Model View, Con
3 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Understanding the difference between Spring JDBC and Spring Data JDBC is important for choosing the right approach to interact with relational databases in Spring Boot applications. Both frameworks serve the same purpose but differ significantly in terms of abstraction, ease of use, and developer pr
5 min read
Best Practices For Structuring Spring Boot Application
Spring Boot is built on top of the conventional spring framework. So, it provides all the features of spring and is yet easier to use than spring. In this article, we are going to see how one should start and structure his Spring Boot application. Prerequisites: Good knowledge of Java.Basic knowledg
3 min read
Spring Boot - Start/Stop a Kafka Listener Dynamically
In a Spring Boot application, Kafka Listeners start automatically once the application launches and they listen for messages from Kafka topics. But there are many scenarios where we might need to dynamically start or stop a Kafka listener based on certain conditions. This can be achieved using Kafka
7 min read
How To Dockerize A Spring Boot Application With Maven ?
Docker is an open-source containerization tool that is used for building, running, and managing applications in an isolated environment. It facilitates the developers to bundles its software, libraries, and configuration files. The Docker facilitates with isolating the one container from another. In
12 min read