How to Send Mail Spring Boot Example - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
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
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>

Here I am going to implement a Simple Spring Boot Example to send a mail and also to send attachments through the 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 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
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

Create Spring Rest Controller to implement mail sending 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!";
    }
}

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 went well, you should have to see the Mail Sent Success! Message on your browser. Then check your mail inbox to confirm.
We can also send the email with attachments like below. Add the below method to Controller and run the application.
@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.
Access the below endpoint URL to send mail with attachments:
http://localhost:8080/sendMailAt
Happy Learning 🙂

Simple Spring Boot Example
Spring Boot Apache ActiveMq In Memory Example
Spring Boot Environment Properties reading based on activeprofile
MicroServices Spring Boot Eureka Server Example
Spring Boot MVC Example Tutorials
Spring Boot RabbitMQ Message Publishing Example
External Apache ActiveMQ Spring Boot Example
Spring Boot Validation Login Form Example
SSL Spring Boot HTTPs Enabling Example
Spring Boot RabbitMQ Consumer Messages Example
Spring Boot How to change the Tomcat to Jetty Server
Sending Spring Boot Kafka JSON Message to Kafka Topic
Spring Boot MongoDB + Spring Data Example
Spring Boot JPA Integration Example
Spring Boot Hibernate Integration Example

Simple Spring Boot Example
Spring Boot Apache ActiveMq In Memory Example
Spring Boot Environment Properties reading based on activeprofile
MicroServices Spring Boot Eureka Server Example
Spring Boot MVC Example Tutorials
Spring Boot RabbitMQ Message Publishing Example
External Apache ActiveMQ Spring Boot Example
Spring Boot Validation Login Form Example
SSL Spring Boot HTTPs Enabling Example
Spring Boot RabbitMQ Consumer Messages Example
Spring Boot How to change the Tomcat to Jetty Server
Sending Spring Boot Kafka JSON Message to Kafka Topic
Spring Boot MongoDB + Spring Data Example
Spring Boot JPA Integration Example
Spring Boot Hibernate Integration Example






sunith
August 23, 2018 at 11:37 am - Reply 

how can we send through our form









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









VuThuy
November 19, 2018 at 10:02 pm - Reply 

Thanks you.









ghjghj
June 20, 2020 at 5:44 pm - Reply 

kkkk










sunith
August 23, 2018 at 11:37 am - Reply 

how can we send through our form




how can we send through our form





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




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





VuThuy
November 19, 2018 at 10:02 pm - Reply 

Thanks you.




Thanks you.





ghjghj
June 20, 2020 at 5:44 pm - Reply 

kkkk




kkkk
 


Δ
 Spring Boot – Hello World
 Spring Boot – MVC Example
 Spring Boot- Change Context Path
 Spring Boot – Change Tomcat Port Number
 Spring Boot – Change Tomcat to Jetty Server
 Spring Boot – Tomcat session timeout
 Spring Boot – Enable Random Port
 Spring Boot – Properties File
 Spring Boot – Beans Lazy Loading
 Spring Boot – Set Favicon image
 Spring Boot – Set Custom Banner
 Spring Boot – Set Application TimeZone
 Spring Boot – Send Mail
 Spring Boot – FileUpload Ajax
 Spring Boot – Actuator
 Spring Boot – Actuator Database Health Check
 Spring Boot – Swagger
 Spring Boot – Enable CORS
 Spring Boot – External Apache ActiveMQ Setup
 Spring Boot – Inmemory Apache ActiveMq
 Spring Boot – Scheduler Job
 Spring Boot – Exception Handling
 Spring Boot – Hibernate CRUD
 Spring Boot – JPA Integration CRUD
 Spring Boot – JPA DataRest CRUD
 Spring Boot – JdbcTemplate CRUD
 Spring Boot – Multiple Data Sources Config
 Spring Boot – JNDI Configuration
 Spring Boot – H2 Database CRUD
 Spring Boot – MongoDB CRUD
 Spring Boot – Redis Data CRUD
 Spring Boot – MVC Login Form Validation
 Spring Boot – Custom Error Pages
 Spring Boot – iText PDF
 Spring Boot – Enable SSL (HTTPs)
 Spring Boot – Basic Authentication
 Spring Boot – In Memory Basic Authentication
 Spring Boot – Security MySQL Database Integration
 Spring Boot – Redis Cache – Redis Server
 Spring Boot – Hazelcast Cache
 Spring Boot – EhCache
 Spring Boot – Kafka Producer
 Spring Boot – Kafka Consumer
 Spring Boot – Kafka JSON Message to Kafka Topic
 Spring Boot – RabbitMQ Publisher
 Spring Boot – RabbitMQ Consumer
 Spring Boot – SOAP Consumer
 Spring Boot – Soap WebServices
 Spring Boot – Batch Csv to Database
 Spring Boot – Eureka Server
 Spring Boot – MockMvc JUnit
 Spring Boot – Docker Deployment