Spring boot

Spring boot email sending example

Spring Boot send email using gmail account

The Spring Framework provides an easy abstraction for sending email by using the JavaMailSender interface, and Spring Boot provides auto-configuration for it as well as a starter module.

Configure your Gmail account for sending email

By default, gmail does not allow less secure apps to get authenticated. You need to turn on the option in you gmail account to allow less secure apps to get authenticated.

Follow these steps:

1.Login to Gmail.
2.Access the URL as https://www.google.com/settings/security/lesssecureapps
3.Select “Turn on”

Configure dependency (pom.xml)

Add spring boot email starter dependency in your pom.xml or build.gradle

<?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.2.6.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.candidjava.spring.boot</groupId>
	<artifactId>spring-boot-send-email</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-boot-send-email</name>
	<description>SMTP sending email</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>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Spring boot email configuration (application.yml)

Configure host, SMTP protocol, user credential, etc. in your application.properties or yml file

server:
   port: 9090
spring:
   mail:
      host: smtp.gmail.com
      port: 587
      username: sample@gmail.com
      password: samplepassword@123
      properties:
         mail:
            smtp:
               auth: true
               connectiontimeout: 5000
               timeout: 5000
               writetimeout: 5000
               starttls:
                  enable: true

Send Email using JavaMailSender (EmailController.java)

Extended MailSender interfaces for JavaMail, supporting MIME messages both as direct arguments and through preparation callbacks. Typically used in conjunction with the MimeMessageHelper class for convenient creation of JavaMail MimeMessages, including attachments, etc.

Clients should talk to the mail sender through this interface if they need mail functionality beyond SimpleMailMessage. The production implementation is JavaMailSenderImpl; for testing, mocks can be created based on this interface. Clients will typically receive the JavaMailSender reference through dependency injection.

The recommended way of using this interface is the MimeMessagePreparator mechanism, possibly using a MimeMessageHelper for populating the message. See MimeMessageHelper’s javadoc for an example.

The entire JavaMail Session management is abstracted by the JavaMailSender. Client code should not deal with a Session in any way, rather leave the entire JavaMail configuration and resource handling to the JavaMailSender implementation. This also increases testability.

A JavaMailSender client is not as easy to test as a plain MailSender client, but still straightforward compared to traditional JavaMail code: Just let createMimeMessage() return a plain MimeMessage created with a Session.getInstance(new Properties()) call, and check the passed-in messages in your mock implementations of the various send methods.

package emailApplication.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmailController {
 @Autowired
 private JavaMailSender javaMailSender;

 @GetMapping("/send")
 public void create() {
  SimpleMailMessage msg = new SimpleMailMessage();
  msg.setTo("sample@gmail.com");
  msg.setSubject("Testing from Spring Boot");
  msg.setText("Hello World \n Spring Boot Email");
  javaMailSender.send(msg);
  System.out.println("Mail Sent Successfully...");
 }
}

Launch as Spring boot application

package emailApplication;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootSendEmailApplication {

 public static void main(String[] args) {
  SpringApplication.run(SpringBootSendEmailApplication.class, args);
 }

}

Download

Download source code from my github account Click here