In this tutorial, I am going to show how to send mail with Spring Boot rest service.

Technologies used :

  • Spring_Boot_1.5.9.RELEASE
  • Spring-Boot-Starter-Mail
  • Java 8

Spring Boot Mail Dependency :

To send a mail from spring boot application, we should add the below dependency in pom.xml

mail dependency in pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

Spring Boot Mail Example :

Here I am going to implement a Simple Spring Boot Example to send a mail and also to send attachments through the mail.

Project Structure :

Spring Boot Mail Example
pom.xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.onlinetutorilspoint</groupId>
<artifactId>SpringBoot_Mail_Example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>SpringBoot_Mail_Example</name>
<description>Spring Boot Mail Example</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath />
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<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>

Configure SMTP Properties in Spring Boot application.properties

application.properties
spring.mail.host=smtp.gmail.com
spring.mail.port=587
[email protected]
spring.mail.password=password (App-Password generated from google tool)
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
Note: The password mentioned above is an app-specific password, you should have to generate your application password from google here. And you should specify the generated password on the above configurations. For more details on Gmail SMTP go through this document.

Create Spring Rest Controller to implement mail sending logic :

SimpleMailController :

SimpleMailController.java
package com.onlinetutorilspoint;

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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SimpleMailController {
    @Autowired
    private JavaMailSender sender;

    @RequestMapping("/sendMail")
    public String sendMail() {
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);

        try {
            helper.setTo("[email protected]");
            helper.setText("Greetings :)");
            helper.setSubject("Mail From Spring Boot");
        } catch (MessagingException e) {
            e.printStackTrace();
            return "Error while sending mail ..";
        }
        sender.send(message);
        return "Mail Sent Success!";
    }
}
Application.java
package com.onlinetutorilspoint;

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

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

Run the Application :

console
D:\> mvnw spring-boot:run

Or (Ubuntu)

$ mvn spring-boot:run

Now you can access the below endpoint URL for send Mail :

http://localhost:8080/sendMail

If everything went well, you should have to see the Mail Sent Success! Message on your browser. Then check your mail inbox to confirm.

Spring Boot Mail Example 2

Spring Boot Mail With Attachment :

We can also send the email with attachments like below. Add the below method to Controller and run the application.

SimpleMailController.java
@RequestMapping("/sendMailAtt")
    public String sendMailAttachment() throws MessagingException {
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true);
        try {
            helper.setTo("[email protected]");
            helper.setText("Greetings :)\n Please find the attached docuemnt for your reference.");
            helper.setSubject("Mail From Spring Boot");
            ClassPathResource file = new ClassPathResource("document.PNG");
            helper.addAttachment("document.PNG", file);
        } catch (MessagingException e) {
            e.printStackTrace();
            return "Error while sending mail ..";
        }
        sender.send(message);
        return "Mail Sent Success!";
    }

Use the MimeMessageHelper(MimeMessage mimeMessage, boolean multipart) to enable multipart mode.

Note: To make this example as simple, I am reading the attachment from the classpath resource. The real-time use case might be upload a document from the client (Browser) by using file upload functionality. I have discussed how to upload files from spring boot in previous tutorials. You can integrate these two examples and make it as a real-time scenario.

Access the below endpoint URL to send mail with attachments:

http://localhost:8080/sendMailAt

Spring Boot Mail Example 3

Download Source from GIT:

Happy Learning 🙂