Spring Mail Sending Email Attachment Configuration Example

摘要: This tutorial demonstrates how to send an email with attachment using spring framework. We can add an attachment to a MimeMessage using the MimeMessageHelper.

This tutorial demonstrates how to send an email with attachment using spring framework. We can add an attachment to a MimeMessage using the MimeMessageHelper.

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.

We can add an attachment to an email using the MimeMessageHelper.addAttachment() method. We need to pass in the filename and the resource as arguments. The content type will be determined by the name of the given content file. Do not use this for temporary files with arbitrary filenames (possibly ending in ‘.tmp’ or the like)!

package com.memorynotfound.mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

public class EmailService {

    private JavaMailSender emailSender;

    public void sendSimpleMessage(Mail mail) throws MessagingException {

        MimeMessage message = emailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);


        helper.addAttachment("attachment-document-name.jpg", new ClassPathResource("memorynotfound-logo.jpg"));




Spring Mail – Sending Email Attachment Configuration 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 Email Attachment Configuration Example");

        Mail mail = new Mail();
        mail.setFrom("[email protected]");
        mail.setTo("[email protected]");
        mail.setSubject("Sending Email Attachment Configuration Example");
        mail.setContent("This tutorial demonstrates how to send an email with attachment 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 14:56:22.746  INFO 49549 --- [           main] com.memorynotfound.mail.Application      : Spring Mail - Sending Email Attachment Configuration Example

Received Email

If your configuration is correct, you should receive the following email in your inbox.


上一篇: Spring Mail Sending Email with Inline Attachment Example
下一篇: Spring Mail Sending Simple Email with JavaMailSender Example
 评论 ( What Do You Think )


  • 微信公众号

  • 我的微信


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

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

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