Spring + Gmail SMTP: Send Email with Attachment using Annotation
February 25, 2022
On this page, we will learn sending email using Spring and Gmail SMTP. We will send simple email and email with attachment using annotation in our example. To test the Gmail SMTP in our local environment, we need to enable our Gmail account less secure otherwise email will be blocked. To send email, Spring provides following APIs.
JavaMailSenderImpl
MimeMessage
MimeMessageHelper
FileSystemResource
In our example, we will understand how to use these API to send email.
Contents
1. Technologies Used
1. Java2. Eclipse
3. Gmail Id
4. Internet
2. Gradle File
build.gradleapply plugin: 'java' apply plugin: 'eclipse' archivesBaseName = 'Concretepage' version = '1.0-SNAPSHOT' repositories { maven { url "https://repo.spring.io/libs-release" } mavenLocal() mavenCentral() } dependencies { compile 'javax.mail:mail:1.4.7' compile 'jaf:activation:1.0.2' compile 'org.springframework.boot:spring-boot-starter:1.2.0.RELEASE' compile 'org.springframework:spring-context-support:4.1.3.RELEASE' }
3. Configuration File for JavaMailSenderImpl
Spring providesJavaMailSenderImpl
that performs email related settings for production and local environment. We need to initialize it as below
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
setHost(): Provide host used to send email. If Gmail, then we will write smtp.gmail.com.
setPort(): Set the port. If using Gmail, we can use it as 587 for TLS and 465 for SSL.
setUsername(): Set username. If using Gmail account, we need to use <username>@gmail.com.
setPassword(): Use your email password. If using Gmail, then use your gmail account password.
getJavaMailProperties(): To set Java mail properties, we use this method and gets java.util.Properties as return type in which we put the properties like mail.transport.protocol, mail.smtp.auth, mail.smtp.starttls.enable etc.
Find the configuration class of our demo.
AppConfig.java
package com.concretepage; import java.util.Properties; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.context.annotation.Bean; import org.springframework.mail.javamail.JavaMailSenderImpl; @Configurable public class AppConfig { @Bean public JavaMailSenderImpl javaMailSenderImpl(){ JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost("smtp.gmail.com"); mailSender.setPort(587); //Set gmail email id mailSender.setUsername("<username>@gmail.com"); //Set gmail email password mailSender.setPassword("password"); Properties prop = mailSender.getJavaMailProperties(); prop.put("mail.transport.protocol", "smtp"); prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.starttls.enable", "true"); prop.put("mail.debug", "true"); return mailSender; } }
4. Make Gmail Account Less Secure
To send email using non Gmail Tool on local, we need to make our Gmail account less secure, otherwise we will get exception asAuthentication failed; nested exception is javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted.
To avoid the above error, we need to set our Gmail account less secure. To do this, follow below steps.
1. Login to Gmail.
2. Access the URL as https://www.google.com/settings/security/lesssecureapps
(This setting is no longer available)
3. Select "Turn on"
Find the screen shot of the configuration.
5. Send Simple Email
TheMimeMessage
is used to create mime style email message. The MimeMessageHelper
helps to populate MimeMessage
. We instantiate these classes as below.
MimeMessage mimeMessage = JavaMailSenderImpl.createMimeMessage(); MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage);
MimeMessageHelper
methods to send the email.
setFrom(): Set sender email.
setTo(): Set recipient email.
setSubject(): Set the subject line of the email.
setText(): Write text to be sent as an email.
addAttachment(): Add attachment.
addCc(): Add cc recipient.
addBcc(): Add bcc recipient.
Find the class to send simple email.
SendSimpleMail.java
package com.concretepage; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; public class SendSimpleMail { public static void main(String[] args) throws MessagingException { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class); ctx.refresh(); JavaMailSenderImpl mailSender = ctx.getBean(JavaMailSenderImpl.class); MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage); mailMsg.setFrom("<username>@gmail.com"); mailMsg.setTo("<username>@gmail.com"); mailMsg.setSubject("Test mail"); mailMsg.setText("Hello World!"); mailSender.send(mimeMessage); System.out.println("---Done---"); } }
Subject: Test mail MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Hello World! . 250 2.0.0 OK 1424882435 uc10sm4970878pbc.87 - gsmtp QUIT 221 2.0.0 closing connection uc10sm4970878pbc.87 - gsmtp ---Done---
6. Send Email with Attachment
To send email with attachment, createMimeMessageHelper
enabling multipart by passing true parameter while initializing.
MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage, true);
FileSystemResource
and pass it to addAttachment()
method of MimeMessageHelper
.
FileSystemResource file = new FileSystemResource(new File("D:/cp/pic.jpg")); mailMsg.addAttachment("myPic.jpg", file);
package com.concretepage; import java.io.File; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; public class SendMailwithAttachment { public static void main(String[] args) throws MessagingException { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class); ctx.refresh(); JavaMailSenderImpl mailSender = ctx.getBean(JavaMailSenderImpl.class); MimeMessage mimeMessage = mailSender.createMimeMessage(); //Pass true flag for multipart message MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage, true); mailMsg.setFrom("<username>@gmail.com"); mailMsg.setTo("<username>@gmail.com"); mailMsg.setSubject("Test mail with Attachment"); mailMsg.setText("Please find Attachment."); //FileSystemResource object for Attachment FileSystemResource file = new FileSystemResource(new File("D:/cp/pic.jpg")); mailMsg.addAttachment("myPic.jpg", file); mailSender.send(mimeMessage); System.out.println("---Done---"); } }