Spring boot mail sender tutorial - Email sender example with SMTP

Today we will see how we can send mail in the spring boot application. We will need a Gmail account using which we will send an email.


Let's create a new spring boot project and build a Rest endpoint where we will send receiver mail id and message, subject in the request body.


Maven dependency


Below are spring boot mail dependency for sending and receiving mail.

<?xml version="1.0" encoding="UTF-8"?>
<project
	xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.6</version>
		<relativePath />
		<!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>Springboot-mailSender</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Springboot-mailSender</name>
	<description>Example for Mail sending in Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.22</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>


Create Model Class


Let's create the model class. We have used the Lombok library to reduce boilerplate code such as getter and setter, tostring.


Annotating the POJO model class with the @Data annotation will include @ToString, @EqualsAndHashCode, @Getter / @Setter, and @RequiredArgsConstructor.


import lombok.Data;

@Data
public class MailMessage {

	private String sendTo;
	private Message message;
	
}

import lombok.Data;

@Data
public class Message {

	private String subject;
	private String message;
	
}


Create Mail service


We will use the spring JavaMailSender interface to send mail. The JavaMailSender supports MIME messages. The MimeMessageHelper class handles the creation of JavaMail MimeMessages, including attachments, etc.


import java.io.IOException;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.example.demo.model.MailMessage;

@Service
public class EmailService {

  @Autowired
  private JavaMailSender javaMailSender;

  public void sendEmail(MailMessage mailMessage) throws MessagingException {
    MimeMessage msg = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(msg, true);
    helper.setTo(mailMessage.getSendTo());
    helper.setSubject(mailMessage.getMessage().getSubject());
    helper.setText(mailMessage.getMessage().getMessage());
    javaMailSender.send(msg);
  }

  public void sendEmailWithAttachment(MailMessage mailMessage)
  throws MessagingException, IOException {

    MimeMessage msg = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(msg, true);
    helper.setTo(mailMessage.getSendTo());
    helper.setSubject(mailMessage.getMessage().getSubject());
    helper.setText(mailMessage.getMessage().getMessage());

    //		helper.addAttachment("add attachment here", bds);
    javaMailSender.send(msg);
  }
}


Add properties for Mail sender


The following properties should be added to the application.properties file.


#logging
logging.level.root=info

#Mail
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your mailid  
spring.mail.password=password
spring.mail.tls=true

#spring.mail.properties.mail.debug=true
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000

# TLS , port 587
# SSL, post 465
#spring.mail.properties.mail.smtp.socketFactory.port = 465
#spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.trust=smtp.gmail.com


Create Controller

Now let's create a GET endpoint to send mail which takes the request body containing the message, subject, and receiver mail id.



import javax.mail.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.example.demo.model.MailMessage;
import com.example.demo.service.EmailService;

@Controller
public class SendMailController {

  @Autowired
  private EmailService emailService;

  @GetMapping(path = "/sendmail")
  public ResponseEntity<String> sendMail(@RequestBody MailMessage mailMessage) throws MessagingException {
    System.out.println("Request body " + mailMessage);
    emailService.sendEmail(mailMessage);
    return ResponseEntity.ok().body("Mail sent successfully");
  }
}


Let test our code by sending mail id and message, subject in the request body. Open Postman and send the request.


Spring boot mail sender example using JavaMailSender  template


Open your google email and see you will received a mail.


Spring boot mail sender example coderhandbook


full code can be found at the GIT repository.

Post a Comment

Previous Post Next Post

Recent Posts

Facebook