Spring Mail Sending Simple Email with JavaMailSender Example
In this tutorial we demonstrate how to send a simple email using spring mail and spring boot. First we configure our email properties using a YAML or Properties file.
Project Structure
Our project structure looks like the following:
Maven Dependencies
We use Apache Maven to manage our project dependencies. Make sure the following dependencies reside on your class-path.
<?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.memorynotfound.mail</groupId> <artifactId>simple-mail</artifactId> <version>1.0.0-SNAPSHOT</version> <url>https://memorynotfound.com</url> <name>Spring LDAP - ${project.artifactId}</name> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.7.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <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> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
Email Configuration Properties
We can use two types of configuration files. Both files reside on the classpath located in the src/main/resources folder. The first and my favorite is application.yml file. I like this type because it has a better structure than the other and you’ll have to type less.
# application.yml spring: mail: default-encoding: UTF-8 host: smtp.gmail.com username: [email protected] password: secret port: 587 properties: mail: smtp: auth: true starttls: enable: true protocol: smtp test-connection: false
The second option you can use is the application.properties file.
# application.properties spring.mail.default-encoding=UTF-8 spring.mail.host=smtp.gmail.com [email protected] spring.mail.password=secret spring.mail.port=587 spring.mail.protocol=smtp spring.mail.test-connection=false spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true
Mail Object
We are using this Mail object to pass as an argument for our EmailService to encapsulate the details of an email message and content.
package com.memorynotfound.mail; public class Mail { private String from; private String to; private String subject; private String content; public Mail() { } public Mail(String from, String to, String subject, String content) { this.from = from; this.to = to; this.subject = subject; this.content = content; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "Mail{" + "from='" + from + '\'' + ", to='" + to + '\'' + ", subject='" + subject + '\'' + ", content='" + content + '\'' + '}'; } }
Creating Email Service Sender
Now lets create a service that’ll be responsible for sending the emails out. We have created a method called sendSimpleMessage() which takes a Mail argument. First we create a SimpleMailMessage and assign the properties of the Mail object to it. Next, we use the JavaMailSender which Spring Boot automatically Initialized with the properties found in the above configuration files.
package com.memorynotfound.mail; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @Service public class EmailService { @Autowired private JavaMailSender emailSender; public void sendSimpleMessage(final Mail mail){ SimpleMailMessage message = new SimpleMailMessage(); message.setSubject(mail.getSubject()); message.setText(mail.getContent()); message.setTo(mail.getTo()); message.setFrom(mail.getFrom()); emailSender.send(message); } }
Spring Mail – Sending Simple Email with JavaMailSender Example
We are using Spring Boot to bootstrap our application. When the application is invoked we simply create a new Mail object and send it using our previously created EmailService
package com.memorynotfound.mail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application implements ApplicationRunner { private static Logger log = LoggerFactory.getLogger(Application.class); @Autowired private EmailService emailService; public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } @Override public void run(ApplicationArguments applicationArguments) throws Exception { log.info("Spring Mail - Sending Simple Email with JavaMailSender Example"); Mail mail = new Mail(); mail.setFrom("[email protected]"); mail.setTo("[email protected]"); mail.setSubject("Sending Simple Email with JavaMailSender Example"); mail.setContent("This tutorial demonstrates how to send a simple email using Spring Framework."); emailService.sendSimpleMessage(mail); } }
Example Output
The previous application prints the following output to the console. If you have correctly configured your smtp client, you should have received an incoming email.
Warning – it’s possible you’re not able to connect to your host when you are behind a company firewall or proxy. In that case you need to contact your company administrator and work out from where you’re able to access this smtp server.
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.7.RELEASE) 2017-10-04 13:47:36.748 INFO 47502 --- [ main] com.memorynotfound.mail.Application : No active profile set, falling back to default profiles: default 2017-10-04 13:47:37.739 INFO 47502 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2017-10-04 13:47:37.760 INFO 47502 --- [ main] com.memorynotfound.mail.Application : Spring Mail - Sending Simple Email with JavaMailSender Example
Received Email
If your configuration is correct, you should receive the following email in your inbox.
Download
From:一号门
COMMENTS