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" 
    <!-- Java Mail API -->
    <!-- Spring framework -->

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();

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"
<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">
       	      <prop key="mail.smtp.auth">true</prop>
       	      <prop key="mail.smtp.starttls.enable">true</prop>
<bean id="mailMail" class="com.mkyong.common.MailMail">
	<property name="mailSender" ref="mailSender" />

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]",
    		   "Testing only \n\n Hello Spring Email Sender");

Download Source Code

Tags :
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.
My website mkyong.com is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time we had server downtime. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts