SPRING BOOT:: Sending Email through SMTP


Spring boot provide the ability to send email through SMTP using JAVA Mail library. Here we are explaining step by step.

Prerequisites:

Before you begin, make sure you have the following tools and dependencies installed:

  • Java JDK (8 or higher)
  • Spring Boot

Step-by-Step Implementation

Step 1: Setup Spring Boot Application

If you do not have spring boot application then got to spring initializr  and build the project. While building the project then add given dependency.

  1. Spring Boot starter Mail
  2. Spring Web
  3. Lombok

Step 2: Spring Boot configuration
Go to application.properties file and configure given properties.

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=GMAIL-MAIL-ID
spring.mail.password=APP-PASSWORD
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

How to generate APP-PASSWORD from GMAIL

  • Go to your google account as per given screenshot

  • Go to account and search app password then getting given screen as per screenshot.

  • Here you can create app then generated auto password, you can copy this password. Above password is the APP-PASSWORD.
  • GMAIL-MAIL-ID is your gmail emailId.

Step 2: Create given packages under application.

  • controller
  • service
  • dto

Step 3: Go to dto package and create EmailDetails class

@Setter
@Getter
public class EmailDetails {
    private String recipient;
    private String msgBody;
    private String subject;
    private String attachment;
}

Step 4: Go to controller package and create EmailController class

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 com.example.mail.dao.EmailDetails;
import com.example.mail.service.EmailService;

@RestController
public class EmailController {
	
	@Autowired
	private EmailService emailService;
	
	// Sending email with attachment
    @PostMapping("/sendMailWithAttachment")
    public String sendMailWithAttachment(@RequestBody EmailDetails details){
        String status = emailService.sendMailWithAttachment(details);
        return status;
    }
}

Step 5: Go to Service package and create EmailService class.

import java.io.File;
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;
import com.example.mail.dao.EmailDetails;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;

@Service
public class EmailService {
	
	@Autowired 
	private JavaMailSender javaMailSender;
	
	@Value("${spring.mail.username}") 
	private String sender;
	 
	 public String
	    sendMailWithAttachment(EmailDetails details)
	    {
	        // Creating a mime message
	        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
	        MimeMessageHelper mimeMessageHelper;
	        try {
	            // Setting multipart as true for attachments to
	            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!!!";
	        }
	    }
}

Now you can run your application and run given restApi from postman.

For send mail 

  • http://localhost:8080/sendMailWithAttachment
  • API TYPE:- POST
  • Body:- {“recipient”: “xxxx@gmail.com”, “msgBody”: “This is the testing mail via spring boot”, “subject”: “Spring boot test mail with attachment”, “attachment”: “C:\\Users\\xxx\\OneDrive\\Documents\\xxx.png”}

Download complete code here