How to Send Mail Spring Boot Example

By | 2019-04-20T15:48:57+05:30 January 1st, 2018|Spring Boot|

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
spring.mail.username=Your-Mail@gmail.com
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("demo@gmail.com");
            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("demo@gmail.com");
            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 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

3 Comments

  1. anaveen4848@gmail.com'
    sunith August 23, 2018 at 11:37 am - Reply

    how can we send through our form

  2. oumayma9404@gmail.com'
    oumayma August 24, 2018 at 2:42 pm - Reply

    I have this problem when i access this URL : http://localhost:8080/sendMail and I receive nothing in the mail
    please help me 🙁

    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 587, isSSL false
    220 smtp.gmail.com ESMTP d1-v6sm3890953wrc.52 – gsmtp
    DEBUG SMTP: connected to host “smtp.gmail.com”, port: 587

    EHLO DESKTOP-J3P2SU8
    250-smtp.gmail.com at your service, [197.17.181.43]
    250-SIZE 35882577
    250-8BITMIME
    250-STARTTLS
    250-ENHANCEDSTATUSCODES
    250-PIPELINING
    250 SMTPUTF8
    DEBUG SMTP: Found extension “SIZE”, arg “35882577”
    DEBUG SMTP: Found extension “8BITMIME”, arg “”
    DEBUG SMTP: Found extension “STARTTLS”, arg “”
    DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
    DEBUG SMTP: Found extension “PIPELINING”, arg “”
    DEBUG SMTP: Found extension “SMTPUTF8”, arg “”
    STARTTLS
    220 2.0.0 Ready to start TLS

  3. thuyvvph04809@fpt.edu.vn'
    VuThuy November 19, 2018 at 10:02 pm - Reply

    Thanks you.

Leave A Comment