Spring Mail Sending Email with Inline Attachment Example
This tutorial demonstrates how to send an email with an inline 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" 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 + '\'' + '}'; } }
CID Embedded Images (Inline Images)
You can embed attachment inline inside an email by using CIDs. CIDs or (Content-ID) work by attaching the image to the email you’re sending and then using standard HTML image tags that reference that image to eventually embed it in the email when the user opens it.
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 inline 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; import java.nio.charset.StandardCharsets; @Service public class EmailService { @Autowired private JavaMailSender emailSender; public void sendSimpleMessage(Mail mail) throws MessagingException { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED, StandardCharsets.UTF_8.name()); helper.addAttachment("logo.png", new ClassPathResource("memorynotfound-logo.png")); String inlineImage = "<img src=\"cid:logo.png\"></img><br/>"; helper.setText(inlineImage + mail.getContent(), true); helper.setSubject(mail.getSubject()); helper.setTo(mail.getTo()); helper.setFrom(mail.getFrom()); emailSender.send(message); } }
Note:There are 4 types of multipart modes you can choose from, each mode handles the inline attachment quite differently.
- MimeMessageHelper.MULTIPART_MODE_NO – indicates a non-multipart message.
- MimeMessageHelper.MULTIPART_MODE_MIXED – indicates a multipart message with a single root multipart element of type “mixed”. Texts, inline elements and attachments will all get added to that root element. It is known to work properly on Outlook. However, other mail clients tend to misinterpret inline elements as attachments and/or show attachments inline as well.
- MimeMessageHelper.MULTIPART_MODE_RELATED – indicates a multipart message with a single root multipart element or type “related”. Texts, inline elements and attachments will all get added to that root element. This is the “Microsoft multipart mode”, as natively sent by Outlook It is known to work properly on Outlook, Outlook Express, Yahoo Mail, and to a large degree also on Mac Mail (with an additional attachment listed for an inline element, despite the inline element also show inline). Does not work properly on Lotus Notes (attachments won’t be shown there).
- MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED – indicates a multipart message with a root multipart element “mixed” plus a nested multipart element of type “related”. Texts and inline elements will get added to the nested “related” element, while attachments will get added to the “mixed” root element. This is arguably the most correct MIME structure, according to the MIME spec: it is known to work properly on Outlook, Outlook Express, Yahoo Mail, and Lotus Notes. Does not work properly on Mac Mail. If you target Mac Mail or experience issues with specific mails on Outlook, consider using MULTIPART_MODE_RELATED instead.
Spring Mail – Sending Email with Inline Attachment 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 Email with Inline Attachment Example"); Mail mail = new Mail(); mail.setFrom("[email protected]"); mail.setTo("[email protected]"); mail.setSubject("Sending Email with Inline Attachment Example"); mail.setContent("This tutorial demonstrates how to send an email with inline attachment 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-05 08:35:28.689 INFO 55879 --- [main] com.memorynotfound.mail.Application: Spring Mail - Sending Email with Inline Attachment Example
Received Email
If your configuration is correct, you should receive the following email in your inbox.
Download
From:一号门
COMMENTS