![]() |
VOOZH | about |
Spring Boot provides built-in support for sending emails using the JavaMail API through the Simple Mail Transfer Protocol (SMTP) server. Using the spring-boot-starter-mail dependency, developers can easily configure and send emails from Spring Boot applications.
Follow the steps below to create a Spring Boot application that sends emails using Gmail SMTP.
Create a new project using Spring Initializr.
Project Configuration:
Add Dependencies:
Select the following dependency:
Download the project, extract it, and open it in your IDE.
Add the following configuration in the application.properties file.
The Gmail ID used to log in to your Gmail account can be provided as the username. To generate the password, 2-step verification must be enabled for your Gmail account.
Steps to generate App Password:
Use the generated password in the application.properties file.
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.
Create a class EmailDetails to store email details such as recipient, subject, message body, and attachment.
Create a service interface EmailService that defines methods for sending emails.
The EmailService interface defines two methods:
The Interface and service implementation class is as shown below in example as follows:
EmailService.java
The sendSimpleMail() method is used to send a simple text email, while the sendMailWithAttachment() method is used to send an email with an attachment.
Create the service implementation class EmailServiceImpl.
The JavaMailSender interface is used to send emails. SimpleMailMessage is used for sending simple text emails, while MimeMessage is used to send emails with attachments.
Create a REST controller EmailController that exposes APIs for sending emails.
Run the Spring Boot application and send a request using Postman:
URL:
http://localhost:8080/sendMail
JSON:
{
"recipient": "recipient@gmail.com",
"msgBody": "Hey,\n\nThis is a Simple Email.\n\nThanks",
"subject": "Simple Email Message"
}
Mail received on Gmail is as follows:
Run the Spring Boot application and send a request to:
http://localhost:8080/sendMailWithAttachment
Mail received on Gmail is as follows: