Main Tutorials

Spring – Sending E-mail via Gmail SMTP server with MailSender

Spring comes with a useful ‘org.springframework.mail.javamail.JavaMailSenderImpl‘ class to simplify the e-mail sending process via JavaMail API. Here’s a Maven build project to use Spring’s ‘JavaMailSenderImpl‘ to send an email via Gmail SMTP server.

1. Project dependency

Add the JavaMail and Spring’s dependency.

File : pom.xml


<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mkyong.common</groupId>
  <artifactId>SpringExample</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SpringExample</name>
  <url>http://maven.apache.org</url>
  
  <repositories>
  	<repository>
  		<id>Java.Net</id>
  		<url>http://download.java.net/maven/2/</url>
  	</repository>
  </repositories>
  
  <dependencies>

    <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>3.8.1</version>
             <scope>test</scope>
    </dependency>
    
    <!-- Java Mail API -->
    <dependency>
	    <groupId>javax.mail</groupId>
	    <artifactId>mail</artifactId>
	    <version>1.4.3</version>
    </dependency>
    
    <!-- Spring framework -->
    <dependency>
     	    <groupId>org.springframework</groupId>
	    <artifactId>spring</artifactId>
	    <version>2.5.6</version>
    </dependency>
    
  </dependencies>
</project>

2. Spring’s Mail Sender

A Java class to send email with the Spring’s MailSender interface.

File : MailMail.java


package com.mkyong.common;

import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

public class MailMail
{
	private MailSender mailSender;
	
	public void setMailSender(MailSender mailSender) {
		this.mailSender = mailSender;
	}
	
	public void sendMail(String from, String to, String subject, String msg) {

		SimpleMailMessage message = new SimpleMailMessage();
		
		message.setFrom(from);
		message.setTo(to);
		message.setSubject(subject);
		message.setText(msg);
		mailSender.send(message);	
	}
}

3. Bean configuration file

Configure the mailSender bean and specify the email details for the Gmail SMTP server.

File : Spring-Mail.xml


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
	<property name="host" value="smtp.gmail.com" />
	<property name="port" value="587" />
	<property name="username" value="username" />
	<property name="password" value="password" />
		
	<property name="javaMailProperties">
	   <props>
       	      <prop key="mail.smtp.auth">true</prop>
       	      <prop key="mail.smtp.starttls.enable">true</prop>
       	   </props>
	</property>
</bean>
	
<bean id="mailMail" class="com.mkyong.common.MailMail">
	<property name="mailSender" ref="mailSender" />
</bean>
	
</beans>

4. Run it


package com.mkyong.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App 
{
    public static void main( String[] args )
    {
    	ApplicationContext context = 
             new ClassPathXmlApplicationContext("Spring-Mail.xml");
    	 
    	MailMail mm = (MailMail) context.getBean("mailMail");
        mm.sendMail("[email protected]",
    		   "[email protected]",
    		   "Testing123", 
    		   "Testing only \n\n Hello Spring Email Sender");
        
    }
}

Download Source Code

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
58 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Syed Abid
5 years ago

I am getting multiple mails of the same message , how to fix that ?

subodh
10 years ago

how to send emails using gwt and spring and hibernate.

subodh
10 years ago

how to send emails using gwt and spring.

Riya Jain
5 years ago

this is working on localhost properly but not on server online…please help me

Riya Jain
5 years ago
Reply to  Riya Jain

hii anyone have idea…. mail not sending on server. please help me its urgent

Marcos
6 years ago

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘mailMail’ is defined
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

David
7 years ago

I do try this approach.
It does work. Thanks alot.

NathanR
7 years ago

Hi, is there a way to configure multiple email accounts? example: I would like to send email from [email protected], [email protected] etc. these accounts are real separate accounts that I would like to use. I assume adding the config for one of them and just changing the from will be useless right?

Shailendra Verma
7 years ago

No test case written inside it.

Younis Irshad
8 years ago

ERROR: Exception in thread “main” org.springframework.mail.MailAuthenticationException: Authentication failed;

SOLVED: 1. Login to Gmail. 2. Access the URL as https://www.google.com/settings/security/lesssecureapps
3. Select “Turn on”

Dinesh>
7 years ago
Reply to  Younis Irshad

NFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4038d0: defining beans [mailSender,mailMail,customeMailMessage]; root of factory hierarchy
Exception in thread “main” org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/answer/78754 126sm14504191qkl.24 – gsmtp

at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:416)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:308)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:297)
at com.mkyong.common.MailMail.sendMail(MailMail.java:26)
at com.mkyong.common.App.main(App.java:13)
Caused by: javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/answer/78754 126sm14504191qkl.24 – gsmtp

at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:648)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:583)
at javax.mail.Service.connect(Service.java:291)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:389)

Bittoo
9 years ago

I tried the exact code and getting the following excpetion :—
I checked the username and password and its correct. Please help

Exception in thread “main” org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbs5Z

Adrian
8 years ago
Reply to  Bittoo

I had the same issue. All you have to do is to activate lesssecureapp feature. To do so, sign in your google account and switch on that.

Sanjay jain
9 years ago

Nice article,
I have also used JavaMailSenderImpl 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

Abhi
9 years ago

Hello Sir,
Thanks for the tutorial.
And how to send mail for multiple recepients???
Please suggest me code.
Thank you

Yo yo honey singh
8 years ago
Reply to  Abhi

make arraylist of the address (type.to)

Hm007
9 years ago

But if we combinate this with Apache Activemq ?

Guest
10 years ago

how to resolve this –?

java.lang.NoClassDefFoundError: com/mkyong/common/App
Caused by: java.lang.ClassNotFoundException: com.mkyong.common.App
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
Exception in thread “main”

tartuzet
10 years ago

gracias, muy buen ejemplo

David
10 years ago

Hello,

Would be possible to set the SMTP server dynamically? I want the user to persist this data in an embedded database once the app is deployed and, after that, configure the mailsender.

Thank you in advance and congratulations for this great article 😉

Shruti
10 years ago

Hi,

Thanks for this tutorial. This is really effective.
One issue I am facing while running this code. The mail is getting delivered without the subject and from.
Can you please let me know apart from this code do I need to do anything else.

My Code:
package com.cms.notification.mail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

public class SampleMail {
@Autowired
private MailSender mailSender;

public void sendMail(String from, String to,String subject, String msg){

SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(msg);
mailSender.send(message);

System.out.println(“DONE”);
}

}

Regards,
Shruti

Andrey
10 years ago

Hi. Error in Spring Web MVC. java.lang.NullPointerException.

        Mail mail = new Mail();
        mail.sendMail("[email protected]", "[email protected]", "Spring mail", "Test mail from Spring Framework");
TanViet
11 years ago

I have downloaded your source code but I see your code in this article is quite different from your code in source code. Which code should I refer?

Silvio
11 years ago

Thank you dude!

himanshu
11 years ago

nice tutorial boss

shilpa
11 years ago

Hi I’m using javamailproperties in the mail bean. I want bounced email notification to be send to another address rather than “from” address in the mail. I’m not getting error but bounced mails are not being sent either.
bean properties

 
<bean id="MailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${MAIL_HOST}"/>
        <property name="port" value="${MAIL_PORT}"/>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.debug">true</prop>
                <prop key="mail.transport.protocol">smtp</prop>
                <!--prop key="mail.smtp.auth">false</prop-->
                <prop key="mail.smtp.starttls.enable">false</prop>
                <prop key="mail.smtp.from">[email protected]</prop>
            </props>
        </property>
    </bean>

java mail sender is

public void sendMail(final MailBean p_mailBean) {
        MimeMessagePreparator l_preparator = new MimeMessagePreparator() {

            public void prepare(MimeMessage p_msg) throws Exception {
                //p_msg.setHeader("Return-Path", "<[email protected]>");

                p_msg.setRecipient(RecipientType.TO, new InternetAddress(p_mailBean.getRecipient()));                  
                if (p_mailBean.getFrom() != null && !"".equals(p_mailBean.getFrom())) {
                    p_msg.setFrom(new InternetAddress(p_mailBean.getFrom()));
                } else {
                    p_msg.setFrom(new InternetAddress(getFromAddress()));
                }
                p_msg.setSubject(p_mailBean.getSubject());
                p_msg.setContent(p_mailBean.getText(), "text/html");
            }
        };
        try {            
            this.mailSender.send(l_preparator);
        } catch (MailException me) {
            System.out.println("exception occurred");
            me.printStackTrace();
            //Doesn't rethrow the exception
            logger.error("Error sending mail to " + p_mailBean.getRecipient(), me);
            logger.error(StackTraceHandler.getTrace(me));
        }
    }

can you help me find what is the problem please? I’ve been working on this for 2 days now 🙁
Thank you

Rohit
11 years ago

Nice work mkong!!! Keep it coming

Petri
11 years ago

Hi,

i just followed your tutorial and got a “org.springframework.mail.MailAuthenticationException” but managed to solve it. Problem was that freshly created gmail -account is blocked somehow, tried with my own personal account and problem was gone.

Ankit Kothana
11 years ago

code works fine but mail is not recieved at the other hand. please help..

Gabby
8 years ago
Reply to  Ankit Kothana

Hi, I am having the same problem

patric
11 years ago

I getting the error as below when I am trying the send the email via the spring mvc framework. I could not figure out the problem. Can anyone help me with the solution?

Is the below error meant that I cant access the smtp of the gmail host?

DEBUG: JavaMail version 1.4.3
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 25, isSSL false

Koushik Roy
11 years ago

Is there any way to know whether the email has been successfully delivered or not. I meant to say whether any bounce back message is there?

Just another name
11 years ago

Thanks a lot, it was really useful. There is a

simpleMailMessage

in the project that can be downloaded which isn’t really used (and it’s not used in the example on this page), you may want to delete in there.

KN (Karunakar Neravetla)
11 years ago

Do you know how to get a delivery notificaiton of an email sent by using JavaMailSenderImpl.

I have tried to set the following properties and tried, but it doesn’t work.

true
true
true
ISO-8859-1
“SUCCESS, FAILURE ORCPT=rfc822;[email protected]
HDRS

Bharat
11 years ago

Great Tutorial !!! Thanks Mkyoung !