Here I am going to discuss how we can send email from Spring application which is recently used scenario in software development.
Here I am going to use org.springframework.mail package which provided by the spring framework to support for the mails. There are interfaces and classes for java mail support in spring framework.
- MailSender interface: It is the root interface. It provides basic functionality for sending simple emails.
- JavaMailSender interface: It is the subinterface of MailSender. It supports MIME messages. It is mostly used with MimeMessageHelper class for the creation of JavaMail MimeMessage, with attachment, etc. The spring framework recommends MimeMessagePreparator mechanism for using this interface.
- JavaMailSenderImpl class: It provides the implementation of JavaMailSender interface. It supports JavaMail MimeMessages and Spring SimpleMailMessages.
- SimpleMailMessage class: It is used to create a simple mail message including from, to, cc, subject and text messages.
- MimeMessagePreparator interface: It is the callback interface for the preparation of JavaMail MIME messages.
- MimeMessageHelper class: It is the helper class for creating a MIME message. It offers support for inline elements such as images, typical mail attachments, and HTML text content.
Here to send email message, I used JavaMailSender interface.
First, you have to create a simple maven project. Following is my sample project structure for your reference
First, you have to create a simple maven project. Following is my sample project structure for your reference
Step 1 - Update Maven dependency
As first step developer need to update the pom.xml with the maven dependencies for Java Mail. For that, you can declare spring-boot-starter-mail. This will pull the dependency for your application.
following is my sample POM file with all dependencies
<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</groupId>
<artifactId>email</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>email</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- dependancy for Java mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
</plugin>
</plugins>
</build>
</project>
Step 2 - Create application.property file
The developer needs to add application.properties file into src/main/resources folder. In this file, the developer is creating a number of properties in a single file to run the application. Following are the properties need to send email from the application
- Host
- port
- username
- password
- javaMailProperties
aplication.properties
logging.level.org.springframework.mail=DEBUG spring.mail.host=smtp.gmail.com spring.mail.port=587 spring.mail.username=<Email for send mail> spring.mail.password=<Password> # javaMailProperties 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 spring.mail.properties.mail.smtp.starttls.enable=trueStep 3 - Create a Java class
Then developer need to create java class in src/main/java folderThere are two methods I have implemented one to send mail without attachment and send a mail with an attachment.
In here you can only run one method at a time.
package com.email.service; import java.io.IOException; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.core.io.ClassPathResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; @SpringBootApplication public class MailService implements CommandLineRunner {
@Autowired private JavaMailSender javaMailSender; public static void main(String[] args) { SpringApplication.run(MailService.class, args); } @Override public void run(String... args) throws MessagingException,IOException { System.out.println("Sending Email...!"); //sendEmailWithoutAttachment(); sendEmailWithAttachment(); System.out.println("Emai Sent...!"); } void sendEmailWithoutAttachment() { SimpleMailMessage message = new SimpleMailMessage(); message.setTo("sample@email");// Recivers email message.setSubject("Testing from Spring Boot"); message.setText("Hello World \n Spring Boot Email"); javaMailSender.send(message); } void sendEmailWithAttachment() throws MessagingException, IOException { MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo("sample@mail");// Receivers mail helper.setSubject("Testing from Spring Boot"); helper.setText("<B>Image attached in the email..!</B>", true); helper.addAttachment("Spring.png", new ClassPathResource("ImageToUpload.png")); javaMailSender.send(message); } }
If you want to send the same message into multiple emails you can simply add the multiple receiver's addresses by comma separating each.
Gotcha...
if you use Gmail as sender's mail even though you have done everything correctly you may not able to run the application correctly. You might get the following error once you run the application.
Caused by: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted.
This happens because the sender's mail should turn on the Allow less secure apps in your google account.
How to enable Allow less secure apps on Gmail
- Log in to google account from here
- Navigate to Security tab from the left side menu
- Find Less secure app access section in the right side
Caused by: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted.
- Log in to google account from here
- Navigate to Security tab from the left side menu
- Find Less secure app access section in the right side
- Now you will navigate to the page where you can turn on Allow less secure apps: ON toggle button
Now you will be able to run the application without error.
Very simple sample project you can find from the following URL
https://github.com/ikalani/springboot-email-sample
https://github.com/ikalani/springboot-email-sample



No comments:
Post a Comment