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
.
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.
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;
@Service
public class EmailService {
@Autowired
private JavaMailSender emailSender;
public void sendSimpleMessage(Mail mail) throws MessagingException {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setSubject(mail.getSubject());
helper.setText(mail.getContent());
helper.setTo(mail.getTo());
helper.setFrom(mail.getTo());
helper.addAttachment("attachment-document-name.jpg", new ClassPathResource("memorynotfound-logo.jpg"));
emailSender.send(message);
}
}
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;
@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 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.");
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 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.
References
- Spring Integration – Sending Emails Documentation
- Spring Boot – Sending Emails Documentation
- Spring Boot – Common Application Properties
- JavaMailSender JavaDoc
- SimpleMailMessage JavaDoc
- MimeMessageHelper JavaDoc
- MimeMessageHelper addAttachment() JavaDoc
Springmail is nothing about any other mail. It’s a mail. Here sharing file process is different. For it, you go to settings and activate the file share process. If you want to know it then just browse the site which I give it will helpful for you.
Thanks