Wednesday , January 17 2018
Home / Spring Boot / How to Send Mail Spring Boot Example

How to Send Mail Spring Boot Example

In this tutorial, I am going to show you 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


<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 above-mentioned password for application is not ordinary password it is app specific password, you should generate your own application password from google here. And you should mention that App Password here. For more details on Gmail SMTP go through this document.

Create Spring Rest Controller to implement send mail logic :

SimpleMailController :


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 :

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 done well yo can see the Mail Sent Success! message on your browser. And check your mail inbox.

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 aapplication.


    @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 as possible, I am passing the attachment by reading from classpath itself. Actually, these attachments can be uploaded from 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 a real-time scenario.

Access the below endpoint URL to send mail with attachments :

http://localhost:8080/sendMailAt

Spring Boot Mail Example 3

Happy Learning 🙂

Download Example

About chandrashekhar

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+ ,

Recommended

How To Change Spring Boot Context Path

In this tutorials, I am going to show you how to change the Spring Boot …

Leave a Reply

Your email address will not be published. Required fields are marked *