Spring Boot Send Email With Attachment

Spring Boot Send Email With Attachment

In this article of Spring Boot, We will learn how to send the Emails with attachments in Spring Boot.

We will be using the JavaMailSender API and spring-boot-starter-mail dependency to learn the Spring Boot Send Email with Attachment tutorial.

Let’s get started :

Add Required Maven Dependencies

We need to add the dependency of spring-boot-starter to make it a Spring Boot Project and for sending emails we need to add spring-boot-starter-mail into our project.

Below is our pom.xml after adding the required dependencies :

<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.example</groupId>
	<artifactId>email</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.8.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>
</project>

SMTP Configuration into Spring Boot Project

For sending mails with attachment, first we are required to configure the SMTP into our project.

Setting up SMTP in Spring Boot is very easy, we can configure it in our application.properties file for the below SMTP servers.

SMTP configuration for Gmail

In Spring Boot, we can send the emails using Gmail SMTP server.

Below mentioned properties needs to be added in the project’s application.properties in order to enable and use the Gmail SMTP server.

We have mentioned the username and password for the Gmail SMTP server in the below application.properties. Do not think that it is an ordinary password.

The below mentioned password is an application password which is generated for your google account. You can check How to generate your Google App password here.

Below is our application.properties file setup for Gmail SMTP server:

debug=true
 
spring.mail.host=smtp.gmail.com
spring.mail.port=25

##Login user for the SMTP server
[email protected]

##Login password for the SMTP server
spring.mail.password=xxxxxx
 
# Other properties
spring.mail.properties.mail.debug=true
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
 
# TLS , port 587
spring.mail.properties.mail.smtp.starttls.enable=true
 
# SSL, post 465
#spring.mail.properties.mail.smtp.socketFactory.port = 465
#spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory

As TLS connections are required by some SMTP servers, that’s why we have enabled these properties in the application.properties

  • spring.mail.properties.mail.smtp.starttls.enable and
  • spring.mail.properties.mail.smtp.auth.

SMTP configuration for Outlook

If you have access to the Outlook SMTP server, below are the mentioned properties which you can use to enable the Outlook SMTP to send emails.

If it is a corporate SMTP server, below information can be acquired from your admin.

application.properties :

spring.mail.host=smtp-mail.outlook.com
spring.mail.port=587

##Login user and password for the SMTP server
[email protected]
spring.mail.password=xxxxxx
 
spring.mail.properties.mail.protocol=smtp
spring.mail.properties.mail.tls=true
 
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.ssl.trust=smtp-mail.outlook.com

SMTP configuration for AWS SES

If you have access to the AWS SES SMTP server, below are the mentioned properties which you can use to enable the AWS SES SMTP to send emails.

You can check this Link to find more details on How to configure your AWS settings.

Further, AWS requires to verify your credentials before actually using them. You can verify it in this url.

application.properties :

spring.mail.host=email-smtp.us-east-1.amazonaws.com
spring.mail.port=465

##the username and password
spring.mail.username=XXXX
spring.mail.password=XXXX
 
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.enable=true
 
spring.mail.properties.mail.protocol=smtps
 
spring.mail.properties.mail.smtps.auth=true

Pre-Configured Email Templates

In Spring Boot, We can create email templates and we can reuse again and again. We can use these created email templates to send an email on any specified duration or specific event or to send email periodically.

In the below example of Spring Boot Send Email, we are creating a very ordinary email containing only text. We are creating below email using SimpleMailMessage.

EmailConfiguration.java :

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;
 
@Configuration
public class EmailConfiguration 
{
    @Bean
    public SimpleMailMessage emailTemplate()
    {
        SimpleMailMessage message = new SimpleMailMessage();
        
        message.setTo("[email protected]");
        message.setFrom("[email protected]");
        message.setSubject("Testing the Spring Boot Email");
        message.setText("First successful Email using the Spring Boot");
        
        return message;
    }
}

Send Simple Emails

We have created a class named EmailSendService which is responsible for sending different types of email.

It takes required parameters like to, subject and body and then compose and send the email to recepient.

EmailSendService.java :

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service("emailSendService")
public class EmailSendService 
{
    @Autowired
    private JavaMailSender mailSender;
      
    @Autowired
    private SimpleMailMessage preConfiguredMessage;
  
    //Method to compose and send the Email
    public void sendEMail(String to, String subject, String body) 
    {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(body);
        mailSender.send(message);
    }
  
  //Method to send the Pre Configured Email
    public void sendPreConfiguredMail(String message) 
    {
        SimpleMailMessage mailMessage = new SimpleMailMessage(preConfiguredMessage);
        mailMessage.setText(message);
        mailSender.send(mailMessage);
    }
}

Spring Boot Send Email With Attachment

The Emails having attachments are called as Multimedia emails. These types of emails are send using  MimeMessageHelper. MimeMessageHelper is basically used to configure MimeMessage.

Mime messages basically are the rich text emails.

Below is the code required for sending email with attachments in Spring Boot :

@Autowired
private JavaMailSender mailSender;
 
public void sendEMailWithAttach(String to, String subject, String body, String attachment) 
{
    MimeMessagePreparator preparator = new MimeMessagePreparator() 
    {
        public void prepare(MimeMessage mimeMessage) throws Exception 
        {
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mimeMessage.setFrom(new InternetAddress("[email protected]"));
            mimeMessage.setSubject(subject);
            mimeMessage.setText(body);
             
            FileSystemResource file = new FileSystemResource(new File(attachment));
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.addAttachment("test.jpg", file);
        }
    };
     
    try {
        mailSender.send(preparator);
    }
    catch (MailException ex) {
        System.err.println(ex.getMessage());
    }
}

Send Email with Inline Images

We can also send the Emails containing rich text. Mails including media content and text contain both can be sent using Spring Boot.

To Send these types of email, we are required to use the addInline() method of the MimeMessageHelper.

See Below code :

@Autowired
private JavaMailSender mailSender;
 
public void sendEMailWithInlineData(String to, String subject, String attachment) 
{
    MimeMessagePreparator preparator = new MimeMessagePreparator() 
    {
        public void prepare(MimeMessage mimeMessage) throws Exception 
        {
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mimeMessage.setFrom(new InternetAddress("[email protected]"));
            mimeMessage.setSubject(subject);
             
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
             
            helper.setText("<html><body><img src='cid:id1'></body></html>", true);
             
            FileSystemResource res = new FileSystemResource(new File(attachment));
            helper.addInline("id1", res);
        }
    };
     
    try {
        mailSender.send(preparator);
    }
    catch (MailException ex) {
        System.err.println(ex.getMessage());
    }
}

Spring Boot Send Email – demo

Now we are all done with the configurations.

It’s time to test the application. Below mentioned class needs to be executed to test the Spring Boot send email examples.

MainApp.java :

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class MainApp implements CommandLineRunner 
{
    @Autowired
    private EmailSendService emailSendService;
 
    public static void main(String[] args) {
        SpringApplication.run(MainApp.class, args);
    }
     
    @Override
    public void run(String args[]) 
    {
        emailSendService.sendEMail("[email protected]", "TBS", "Tech Blog Station");
         
        emailSendService.sendPreConfiguredMail("Tech Blog Station");
    }
}

Conclusion

In this article, we have covered the complete topic of Spring Boot Send Email With Attachment and Inline images and also learnt How to send the pre-configured templates with the illustrative examples.

Leave a Reply

Your email address will not be published. Required fields are marked *