Learn to send emails in Spring 5 provided JavaMailSender
interface. Here is a step by step example for sending email via gmail smtp server.
We will use javax.mail
maven dependency to send emails while configuring mail properties in JavaMailSenderImpl
class which implements JavaMailSender
interface.
1. Maven dependencies
Follow maven project creation example for creating a project. Now import spring dependencies along with javax.mail.
<properties> <spring.version>5.2.0.RELEASE</spring.version> <email.version>1.16.18</email.version> </properties> <!-- Spring Context Support --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>${email.version}</version> </dependency>
2. JavaMailSender and Email templates
2.1. Java Configuration
Given is Java configuration for JavaMailSender
which has been configured to use Gmail SMTP settings and we have configured a sample email template preconfigured with sender/reciever emails and email text.
You can customized the configuration as per your need.
import java.util.Properties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; @Configuration public class EmailConfig { @Bean public JavaMailSender getJavaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost("smtp.gmail.com"); mailSender.setPort(25); mailSender.setUsername("admin@gmail.com"); mailSender.setPassword("password"); Properties props = mailSender.getJavaMailProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.debug", "true"); return mailSender; } @Bean public SimpleMailMessage emailTemplate() { SimpleMailMessage message = new SimpleMailMessage(); message.setTo("somebody@gmail.com"); message.setFrom("admin@gmail.com"); message.setText("FATAL - Application crash. Save your job !!"); return message; } }
2.2. XML Configuration
In Spring context file, we will create a generic mail sender service which is capable of sending HTTP messages using gmail’s smtp server.
Also, we are making a pre-configured message which can be instantiated on the fly and use for sending the message.
<beans> <context:component-scan base-package="com.howtodoinjava" /> <!-- SET default mail properties --> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.gmail.com"/> <property name="port" value="25"/> <property name="username" value="admin@gmail.com"/> <property name="password" value="password"/> <property name="javaMailProperties"> <props> <prop key="mail.transport.protocol">smtp</prop> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.starttls.enable">true</prop> <prop key="mail.debug">true</prop> </props> </property> </bean> <!-- We can have some pre-configured messagess also which are ready to send --> <bean id="preConfiguredMessage" class="org.springframework.mail.SimpleMailMessage"> <property name="to" value="somebody@gmail.com"></property> <property name="from" value="admin@gmail.com"></property> <property name="subject" value="FATAL - Application crash. Save your job !!"/> </bean> </beans>
3. Sending emails
This class uses the beans configured in applicationContext.xml
file and use them to send messages.
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.SimpleMailMessage; import org.springframework.stereotype.Service; @Service("emailService") public class EmailService { @Autowired private JavaMailSender mailSender; @Autowired private SimpleMailMessage preConfiguredMessage; /** * This method will send compose and send the message * */ public void sendMail(String to, String subject, String body) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(body); mailSender.send(message); } /** * This method will send a pre-configured message * */ public void sendPreConfiguredMail(String message) { SimpleMailMessage mailMessage = new SimpleMailMessage(preConfiguredMessage); mailMessage.setText(message); mailSender.send(mailMessage); } }
4. Email with attachments and inline resources
4.1. Email attachments
To attach a file with email, use MimeMessageHelper
to attach the file with a MimeMessage
.
public void sendMailWithAttachment(String to, String subject, String body, String fileToAttach) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); mimeMessage.setFrom(new InternetAddress("admin@gmail.com")); mimeMessage.setSubject(subject); mimeMessage.setText(body); FileSystemResource file = new FileSystemResource(new File(fileToAttach)); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.addAttachment("logo.jpg", file); } }; try { mailSender.send(preparator); } catch (MailException ex) { // simply log it and go on... System.err.println(ex.getMessage()); } }
4.2. Inline resources
Sometimes, we may want to attach inline resources such as inline images in email body.
Inline resources are added to the MimeMessage
by using the specified Content-ID. Be sure to first add the text and then the resources. If you are doing it the other way around, it does not work.
public void sendMailWithInlineResources(String to, String subject, String fileToAttach) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); mimeMessage.setFrom(new InternetAddress("admin@gmail.com")); mimeMessage.setSubject(subject); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true); FileSystemResource res = new FileSystemResource(new File(fileToAttach)); helper.addInline("identifier1234", res); } }; try { mailSender.send(preparator); } catch (MailException ex) { // simply log it and go on... System.err.println(ex.getMessage()); } }
5. Demo
Time to test the spring mail sending program code. I am sending two messages from test code. One is instantiated and composed in test class itself, and another one is pre-configured message from applicationContext.xml
file.
import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class SpringEmailTest { public static void main(String[] args) { //Create the application context ApplicationContext context = new FileSystemXmlApplicationContext ("classpath:com/howtodoinjava/core/email/applicationContext.xml"); //Get the mailer instance EmailService mailer = (EmailService) context.getBean("emailService"); //Send a composed mail mailer.sendMail("somebody@gmail.com", "Test Subject", "Testing body"); //Send a pre-configured mail mailer.sendPreConfiguredMail("Exception occurred everywhere.. where are you ????"); } }
Above call will send the emails.
Happy Learning !!
ABCD
correct solution !! its works for me , Thanks
Rohit Kaushik
how can we send a message in a mail conversation using this JavaMailSender
Sachin Raghav
Hi Lokesh,
like i have 5 smtp server’s and i want to do bulk mailing and want to post on each server then how i can achieve it ?
Sachin Raghav
I am using like this now :
String smtpHost=”smtp.gmail.com”;
javaMailSender.setHost(smtpHost);
Properties mailProps = new Properties();
mailProps.put(“mail.smtp.connectiontimeout”, “2000”);
mailProps.put(“mail.smtp.timeout”, “2000”);
mailProps.put(“mail.debug”, “false”);
javaMailSender.setJavaMailProperties(mailProps);
Now i want to post on multiple VIP’s like
String smtpHost=”192.168.xx.xx,192.168.xx.xx,192.168.xx.xx”;
Can you suggest how i can achieve this ?
Lokesh Gupta
I don’t think it’s possible. You should be creating 5 mailsender instances for 5 different hosts.
Vimalsharma
Hi Lokesh
I am using spring 3.2 sprig version, I have new problem in MailSenderImpl exception line
transport.connect(getHost(), getPort(), getUsername(), getPassword()); then how to fix this problem.
Lokesh Gupta
Can you please mention the exact error.
vishwas sampath
Sir,how to check the connections before sending the mail. I have written some logic to execute if connection fails so please tell me how can I achieve it..??
Pranjali
Hi Lokesh ,
Is it applicable for spring Version 3.2.
If not what changes should be there to work it correctly?
Lokesh Gupta
Yes, it should work.
mahender
How to configure mail configurations(port number,smtp server,to address,from address) using json file
sumit khelwal
Hi,
how i can generate oauth2 access token to send mail using smtp gmail server. Above code is works when i set my account less secure app .
thanks in advance
Lokesh Gupta
This may help you. https://stackoverflow.com/questions/12503303/javamail-api-in-android-using-xoauth/12821612#12821612
Kishore
Hi Lokesh,
I am using Spring mail API, Thank you for providing this tutorial. Its very helpful.
I am facing one issue.
If I am send an email to an incorrect email id which does not exists, I am not getting any exceptions.
Could you please provide me any suggestions, like how to track mail sending failed due to email address issues or some other issues?
My Email ID is: xxxxxxxx@gmail.com
Thanks & Regards,
Kishore.
Lokesh Gupta
I do not any solution for this problem right now. Try to find when time permits.
Kamet
Hi Lokesh,
I am getting the following exception even when the user name password are correct :-
Exception in thread “main” org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 534-5.7.14
After getting this exception I got an email from google with subject Google Account: sign-in attempt blocked and asked me to change setting to use less secure setting so that your account is no longer protected by modern security standards. I made the gmail settings changed to less secure and now the code runs fine.
Is there any way to make the gmail setting secured and at the same time sending mail via spring ??
Please suggest.
Lokesh Gupta
I will dig more onto this. Thanks for sharing your experience.
Kamet
Sure lokesh. Thanks 🙂
raj
any update on this.getting same error
Sanjay Jain
Nice explanation Lokesh,
I have also used same implementation for sending mail and it is running successfully.
There is one issue i faced is that, as I am sending some critical data in mail and it gets logged in console.
So is there any way to disable logger for not logging critical mail content or whole mail content ?
Thanks in advance
Sanjay Jain
Hi Lokesh,
Any possible way to restrict logger to log email content on console ?
madhu
hey brother,
what are the external jar s i need to add in order to run this code.
Lokesh Gupta
The required dependencies I have mentioned in pom.xml file. No other external jar required.
madhu
1.when i run MailerTest.java i am getting this error
Publishing failed with multiple errors
Error reading file C:Usersmadu.m2repositoryjavaxmailmail1.4mail-1.4.jar
C:Usersmadu.m2repositoryjavaxmailmail1.4mail-1.4.jar (The system cannot find the file specified)
Error reading file C:Usersmadu.m2repositoryorgspringframeworkspring-expression3.0.5.RELEASEspring-expression-3.0.5.RELEASE.jar
C:Usersmadu.m2repositoryorgspringframeworkspring-expression3.0.5.RELEASEspring-expression-3.0.5.RELEASE.jar (The system cannot find the file specified)
2. where should i add this code
JBoss repository
https://repository.jboss.org/nexus/content/groups/public/
3.0.5.RELEASE
madhu
Can you please provide the code for this example as a Zip.file ,will be more helpful !!!!
Hemant
Hey Lokesh,
How to send mail with own domail ie i don’t want to go with gmail.I have my own domail.I that case what i have to configure.
Lokesh Gupta
Configure your own mail server details in “mailSender” bean.
test test
Hi thank you for this great tutorial I have an error message:Could not autowire field: private org.springframework.mail.MailSender ,Can you help me please :/
Lokesh Gupta
<context:component-scan base-package="..." />
Make sure you have given write path.José Gerontolous
Add:
org.springframework
spring-context-support
3.1.4.RELEASE
alverhothasi
nice tutorial, this is automatic sending to email, i wonder how to overide it to button, so when i click the button the email will be send.. can you help me ?
Renaud L
Hi, I keep having the same error. When I try to send the mail, I’m getting the following error:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn’t connect to host, port: smtp.gmail.com, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection timed out: connect. Failed messages: com.sun.mail.util.MailConnectException: Couldn’t connect to host, port: smtp.gmail.com, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection timed out: connect; message exceptions (1) are:
Failed message 1: com.sun.mail.util.MailConnectException: Couldn’t connect to host, port: smtp.gmail.com, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection timed out: connect
I tried to find a solution on Google without success. I tried the above (with port 110 and 143) but also without success.
Can you please give some more troubleshoot on what might be wrong?
Thanks in advance
Renaud L.
Lokesh Gupta
You must be behind some firewall which is preventing the connection.
Renaud L
Your right about my firewall, after hours I found a port which did the trick for me, port 587. When I posted this question I tried several ports so I thought it was something else. Anyway, I found this port on another website so this may be of use for other people as well.
Thanks
rahul
Sir when I tried to run the code I got the following error.Can you tell me what I need to do more??
And I have used port as 587 but dont know why port 25 is showing here
Exception in thread “main” org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25, response: 421. Failed messages: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25, response: 421; message exception details (1) are:
Failed message 1:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25, response: 421
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1270)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
at javax.mail.Service.connect(Service.java:275)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:389)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:306)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:296)
at com.spring.ApplicationMailer.sendMail(ApplicationMailer.java:26)
at com.spring.TestMailSender.main(TestMailSender.java:21)
Thanks,
Rahul
Lokesh Gupta
It be your firewall which is blocking this port. Try ports 110 and 143.
Ali
Thanks very much for this … very useful.
Is it possible to add encryption to this email using public key encryption ?
thanks
Lokesh Gupta
It should be. I am not able to answer your question immediately. I will try to find out something for you.
Ali
Thanks 🙂
Dan
Very nice. Thank you.
omeganexusmx
Very clear sir!