Home  >  Spring Core

Spring + Gmail SMTP: Send Email with Attachment using Annotation

By Arvind Rai, February 25, 2015
In this page we will learn sending email using Spring and Gmail SMTP. We will send simple email and email with attachment using annotation in spring. 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 API like JavaMailSenderImpl, MimeMessage, MimeMessageHelper and FileSystemResource. In our example we will understand how to use it to send email. We will cover below points.

1. Gradle for java and spring mailing API
2. How to configure less secure Gmail Account for local.
3. Send Simple Email
4. Send Email with Attachment

Software and Other Requirement to run Example

To learn and sending email in real time we should be ready with given requirements.
1. Java 6
2. Eclipse
3. Gmail Id
4. Internet

Gradle to Resolve JAR Dependency to Send Email

To run the email example with spring we need spring and java mail API.
build.gradle
apply 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'
} 

Configuration File for JavaMailSenderImpl

Spring provides org.springframework.mail.javamail.JavaMailSenderImpl which is used to do email related settings for production and local environment. Initialize it as below
JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); 
We can override pre-configured settings using the methods given below.

setHost(): Provide host used to send email. If Gmail, then we will write smtp.gmail.com.
setPort(): Sets the port. If using Gmail, we can use it as 587 for TLS and 465 for SSL.
setUsername(): Sets 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 and puts the properties like mail.transport.protocol, mail.smtp.auth, mail.smtp.starttls.enable etc.

Find the configuration class.
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("arvindraivns06@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;
	}
} 

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 as

Authentication 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
3. Select "Turn on"

Find the screen shot of the configuration.
Spring + Gmail SMTP:  Send Email with Attachment using Annotation

Send Simple Email with MimeMessage and MimeMessageHelper

javax.mail.internet.MimeMessage is used to create mime style email message. org.springframework.mail.javamail.MimeMessageHelper helps to populate MimeMessage. We instantiate these classes as below.
MimeMessage mimeMessage = JavaMailSenderImpl.createMimeMessage();
MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage); 
We need to set MimeMessageHelper methods to send the email.
setFrom(): Sets sender email.
setTo(): Sets recipient email.
setSubject(): Sets 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 which is sending 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("arvindraivns02@gmail.com");
      	   mailMsg.setTo("arvindraivns03@gmail.com");
      	   mailMsg.setSubject("Test mail");
      	   mailMsg.setText("Hello World!");
	   mailSender.send(mimeMessage);
	   System.out.println("---Done---");
	}
} 
Find the output.
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--- 

Send Email with Attachment using MimeMessageHelper and FileSystemResource

To send email with attachment, create MimeMessageHelper enabling multipart. To do it pass true parameter while initializing.
MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage, true); 
To attach a file, create the object of org.springframework.core.io.FileSystemResource and pass it to addAttachment() method of MimeMessageHelper.
FileSystemResource file = new FileSystemResource(new File("D:/cp/pic.jpg"));
mailMsg.addAttachment("myPic.jpg", file); 

SendMailwithAttachment.java
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("arvindraivns02@gmail.com");
      	   mailMsg.setTo("arvindraivns03@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---");
	}
} 
Find the output.
Subject: Test mail with Attachment
MIME-Version: 1.0
Content-Type: multipart/mixed; 
	boundary="----=_Part_0_1230404080.1424883479726"

------=_Part_0_1230404080.1424883479726
Content-Type: multipart/related; 
	boundary="----=_Part_1_1679417766.1424883479748"

------=_Part_1_1679417766.1424883479748
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

Please find Attachment.
------=_Part_1_1679417766.1424883479748--

------=_Part_0_1230404080.1424883479726
Content-Type: image/jpeg; name=myPic.jpg
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=myPic.jpg

/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAACgAA/+4AIUFkb2JlAGTAAAAAAQMA
EAMCAwYAAAbiAAAOaQAAGhf/2wCEABQQEBkSGScXFycyJh8mMi4mJiYmLj41NTU1NT5EQUFBQUFB
REREREREREREREREREREREREREREREREREREREQBFRkZIBwgJhgYJjYmICY2RDYrKzZERERCNUJE
RERERERERERERERERERERERERERERERERERERERERERERERERP/CABEIAaEBHAMBIgACEQEDEQH/
xAC8AAEAAgMBAQAAAAAAAAAAAAAAAQMEBQYCBwEBAQEBAAAAAAAAAAAAAAAAAAECAxAAAQQCAQMC
BAQFBQEAAAAAAAERAgMEFRITFAVQQhAxMiQgMCEGQCNDJUWAQTM0RCIRAAEDAQUCCwUHAwQDAAAA
KcCTIiR+UX
k/BT8ycY6cRGVZBtrusZ34+JSEpgQgIEzAkXqDgAAOUNLUY5TZcQVqRhoQ==
------=_Part_0_1230404080.1424883479726--
.
250 2.0.0 OK 1424883490 ep2sm41742661pbc.78 - gsmtp
QUIT
221 2.0.0 closing connection ep2sm41742661pbc.78 - gsmtp
---Done--- 
Check your email. You will be getting emails. Happy Learning!

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us