Spring boot application to send emails using SMTP protocol
Welcome to my blog post, where I’ll guide you through the process of developing a Spring Boot project to send emails using the Simple Mail Transfer Protocol (SMTP). During my internship period, I had the opportunity to work on this task, and I’m excited to share my knowledge and experiences with you. By the end of this guide, you’ll have a solid understanding of how to integrate email functionality into your Spring Boot projects. So let’s get started!
Setting Up Your Spring Boot Project
To begin, we need to set up a new Spring Boot project. You can initialize your project using Spring Initializer or your preferred IDE if you haven’t already. Ensure to include the necessary dependencies; specifically, you must add Java Mail Sender
for this application. Setting up the project structure correctly is the foundation for our email implementation. In this blog, I am using Spring Initializer. You can give an Artifact name as your preference and generate the zip file.
Now you can unzip the file and open with your prefered IDE, here I’m using IntelliJ IDEA. Your pom.xml
dependancies should look like the following.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Configuring the SMTP Server
Now that our project is set up, we need to configure it to connect to an SMTP server. This server will handle the actual sending of emails. To set the SMTP server details in our project’s configuration files, you need a
- Go to the email account from which you want to send the email.
- Select Manage your Google account.
3. In the search bar, search App passwords
4. Complete the two-step verification if you haven’t done it before.
5. Select app (other in this case) and click Generate.
6. Now you will see the generated app password.
7. Copy that, and you need to paste it into the application properties configurations.
Here’s how you should do it.
Application.properties
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-sender-email@gmail.com
spring.mail.password=copied-app-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.host=smtp.gmail.com
: This line specifies the SMTP server host. In this case, we’re using Gmail’s SMTP server. Change this value if you’re using a different SMTP server.spring.mail.port=587
: Theport
property specifies the port number used to establish a connection with the SMTP server. For Gmail's SMTP server, the recommended port is 587.spring.mail.username=your-sender-email@gmail.com
: Here, you need to provide the email address of the account you want to use as the sender of the emails. Replaceyour-sender-email@gmail.com
with the actual email address you intend to use.spring.mail.password=copied-app-password
: This property requires the password or app-specific password associated with the email account specified in thespring.mail.username
property. For security reasons, it's crucial not to use the account's actual password. Instead, generate an app-specific password from the email service provider and use it here.spring.mail.properties.mail.smtp.auth=true
: Themail.smtp.auth
property is used to enable SMTP authentication. When set totrue
, it indicates that the SMTP server requires authentication before sending emails. This is usually the case for most SMTP servers.spring.mail.properties.mail.smtp.starttls.enable=true
: Themail.smtp.starttls.enable
property enables the use of Transport Layer Security (TLS) when connecting to the SMTP server. When set totrue
, it ensures that the connection is secured using TLS encryption
Implementing the Email Service
With our project and SMTP server configured, it’s time to create the JavaSmtpGmailSenderService
class. This class will act as the central hub for our email functionality. We’ll delve into the implementation details, including how to inject the necessary dependency, JavaMailSender, which provides the interface for sending emails. By encapsulating the email logic within this service class, we ensure a clean separation of concerns and maintainable code.
JavaSmtpGmailSenderService
package com.example.javasmtpgmailsender;
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 JavaSmtpGmailSenderService {
@Autowired
private JavaMailSender emailSender;
public void sendEmail(String toEmail, String subject, String body){
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("your-sender-email@gmail.com");
message.setTo(toEmail);
message.setSubject(subject);
message.setText(body);
emailSender.send(message);
System.out.println("Message sent successfully");
}
}
This service class provides a simple and straightforward way to send emails using SMTP
- The
JavaSmtpGmailSenderService
class is annotated with@Service
, indicating that it's a service component managed by Spring. - The
JavaMailSender
instance is autowired using the@Autowired
annotation. This dependency provides the necessary methods to send emails. - The
sendEmail()
method takes in three parameters:toEmail
(the recipient's email address),subject
(the email subject), andbody
(the email content). - A
SimpleMailMessage
object is created and configured with the sender's email address (setFrom()
), recipient's email address (setTo()
), subject (setSubject()
), and body (setText()
). - The
emailSender.send(message)
line sends the email using theemailSender
instance, which is injected by Spring Boot.
Composing and Sending Emails
Now comes the exciting part—composing and sending emails! You can set the email recipients, subject, and content, and finally, utilize the JavaSmtpGmailSenderService
to send the emails according to your preference.
JavaSmtpGmailSenderApplication
package com.example.javasmtpgmailsender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
@SpringBootApplication
public class JavaSmtpGmailSenderApplication {
@Autowired
private JavaSmtpGmailSenderService senderService;
public static void main(String[] args) {
SpringApplication.run(JavaSmtpGmailSenderApplication.class, args);
}
@EventListener(ApplicationReadyEvent.class)
public void sendMail(){
senderService.sendEmail("receiver-email@gmail.com","This is subject","This is email body");
}
}
This serves as the entry point for the application and includes an event listener to automatically send an email when the application is ready.
- The
JavaSmtpGmailSenderApplication
class is annotated with@SpringBootApplication
, which combines the@Configuration
,@EnableAutoConfiguration
, and@ComponentScan
annotations. - The
JavaSmtpGmailSenderService
instance is autowired using the@Autowired
annotation. This allows the application to access the email sending functionality. - The
main()
method serves as the entry point for your Spring Boot application, where you useSpringApplication.run()
to start the application. - The
sendMail()
method is annotated with@EventListener(ApplicationReadyEvent.class)
, which means it will be triggered when the application is ready to handle requests. - Within the
sendMail()
method, you call thesendEmail()
method from theJavaSmtpGmailSenderService
instance (senderService
). This sends an email with the specified recipient, subject, and body. - By utilizing the
@EventListener(ApplicationReadyEvent.class)
annotation, you ensure that the email is sent automatically when the application is fully started and ready to handle requests.
Demonstration
Source code
Conclusion
Congratulations! You’ve successfully learned how to develop a Spring Boot project to send emails using the SMTP protocol. This guide covered setting up the project, configuring the SMTP server, implementing the Service class, composing and sending emails. Integrating email functionality into your Spring Boot projects can enhance user communication and deliver a more engaging experience.
I hope this blog post has been informative and valuable to you. Feel free to explore further resources and repositories for additional insights. Thank you for joining me on this email-sending journey, and best of luck with your future Spring Boot projects!