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.

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"

    <name>Spring LDAP - ${project.artifactId}</name>





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

    default-encoding: UTF-8
    host: smtp.gmail.com
    username: [email protected]
    password: secret
    port: 587
          auth: true
            enable: true
    protocol: smtp
    test-connection: false

The second option you can use is the application.properties file.

# application.properties

[email protected]

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;

    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;

public class EmailService {

    private JavaMailSender emailSender;

    public void sendSimpleMessage(final Mail mail){
        SimpleMailMessage message = new SimpleMailMessage();



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;

public class Application implements ApplicationRunner {

    private static Logger log = LoggerFactory.getLogger(Application.class);

    private EmailService emailService;

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);

    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.");


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.


上一篇: Spring Mail Sending Email Attachment Configuration Example
下一篇: Spring Boot + Spring LDAP Integration Testing Example
 评论 ( What Do You Think )


  • 微信公众号

  • 我的微信


1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号