Wednesday, October 03, 2012

Sending Email using Spring MailSender and Gmail SMTP Server

Spring provides interface called "MailSender" (org.springframework.mail.MailSender) to send mail.
Developer can use MailSender method send(SimpleMailMessage simpleMessage)and pass SimpleMailMessage with From,To,Subject, and Text set.

MailSender Documentation : MailSender
SimpleMailMessage Documentation : SimpleMailMessage

Java Program to send Mail using Spring MailSender :
package com.anuj.spring.mail;

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

 * @author Anuj Patel
public class NotifyImpl {
    private MailSender mailsender;
    public MailSender getMailsender() {
        return mailsender;
    public void setMailsender(MailSender mailsender) {
        this.mailsender = mailsender;
    public void sendMail(String from, String to, String subject, String message) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

Main Java Program :
package com.anuj.spring.mail;

import org.springframework.context.ApplicationContext;

 * @author Anuj Patel
public class MailApp {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring_mail.xml");

        NotifyImpl notifyImpl = (NotifyImpl) context.getBean("notifyBean");
        String from = "";
        String to = "";
        String Subject = "Spring Mail Demo";
        String message = "This mail is send using Spring Mail";

        notifyImpl.sendMail(from, to, Subject, message);
Please note that If you are working under proxy then you require to set Proxy Details explicitly in code or xml. Spring-Beans.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    <bean id="notifyBean" class="com.anuj.spring.mail.NotifyImpl">        
        <property name="mailsender" ref="mailSender" />
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="" />
 <property name="port" value="587" />
 <property name="username" value="" />
 <property name="password" value="mygmailpassword" />
        <property name="javaMailProperties">
              <prop key="mail.smtp.auth">true</prop>
              <prop key="mail.smtp.starttls.enable">true</prop>


Author : Anuj Patel
Blog :

No comments:

Post a Comment