Home » Java » Enterprise Java » Sending e-mails in Java with Spring – GMail SMTP server example

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Sending e-mails in Java with Spring – GMail SMTP server example

For e-mail sending in Java, the JavaMail API is the standard solution. As the official web page states, “The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications”. The necessary classes are included in the JavaEE platform, but to use it in a standalone JavaSE application you will have to download the corresponding JAR from here.

Note: Unless you’re using Java SE 6, you will also need the JavaBeans Activation Framework (JAF) extension that provides the javax.activation package. We suggest you use version 1.1.1 of JAF, the latest release. JAF is included with Java SE 6.

JavaMail can unfortunately be a little cumbersome and difficult to configure and use. In case you have embraced the Spring framework for your applications, you will be glad to find out that Spring provides a mail abstraction layer. As the reference documentation states, “The Spring Framework provides a helpful utility library for sending email that shields the user from the specifics of the underlying mailing system and is responsible for low level resource handling on behalf of the client.” Great, let’s see now how to leverage this library.

First, create a new Eclipse project named “SpringMailProject”. In the project’s classpath, make sure to include the following libraries (note that the 3.0.2.RELEASE Spring version was used):

  • mail.jar (the core JavaMail classes)
  • org.springframework.asm-3.0.2.RELEASE.jar
  • org.springframework.beans-3.0.2.RELEASE.jar
  • org.springframework.context.support-3.0.2.RELEASE.jar
  • org.springframework.core-3.0.2.RELEASE.jar
  • org.springframework.expression-3.0.2.RELEASE.jar
  • com.springsource.org.apache.commons.logging-1.1.1.jar

Note1: The commons-logging library from Apache is needed and was included in the classpath
Note2: You will also need the Java Activation Framework if you are using Java 1.5 or earlier

We will use MailSender, a Spring interface that defines a strategy for sending simple mails. Since this is just an interface, we need a concrete implementation and that comes in the form of JavaMailSenderImpl. This class supports both JavaMail MimeMessages and Spring SimpleMailMessages.

We will create a simple Spring service that will be used for sending mail. One method will create a SimpleMailMessage on the spot, while the other will use a preconfigured default message. The source code for the service is the following:

package com.javacodegeeks.spring.mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

public class MailService {
    private MailSender mailSender;
    private SimpleMailMessage alertMailMessage;
    public void sendMail(String from, String to, String subject, String body) {
        SimpleMailMessage message = new SimpleMailMessage();
    public void sendAlertMail(String alert) {
        SimpleMailMessage mailMessage = new SimpleMailMessage(alertMailMessage);

The class is just a POJO and its service name is “mailService”, marked by the stereotype Service annotation. The beans wiring strategy used is the one of autowiring, thus the Autowired annotation is used. Note that the autowiring can be performed using both the name and the type of a bean.

The corresponding Spring XML file that bootstraps the container is the following:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"

    <context:component-scan base-package="com.javacodegeeks.spring.mail" />    
    <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="[email protected]"/>
        <property name="password" value="mypassword"/>
        <property name="javaMailProperties">
                <!-- Use SMTP transport protocol -->
                <prop key="mail.transport.protocol">smtp</prop>
                <!-- Use SMTP-AUTH to authenticate to SMTP server -->
                <prop key="mail.smtp.auth">true</prop>
                <!-- Use TLS to encrypt communication with SMTP server -->
                <prop key="mail.smtp.starttls.enable">true</prop>
                <prop key="mail.debug">true</prop>
    <bean id="alertMailMessage" class="org.springframework.mail.SimpleMailMessage">
        <property name="from">            
            <value>[email protected]</value>
        <property name="to">            
            <value>[email protected]</value>
        <property name="subject" value="Alert - Exception occurred. Please investigate"/>

This is a quite simple Spring config file. Some things to mention though:

  • The base package from which the context scanning will start is declared and is set to “com.javacodegeeks.spring.mail”.
  • The “mailSender” bean is declared and a bunch of its properties are appropriately set (use your own SMTP server configuration attributes and credentials).
  • The “alertMailMessage” is a preconfigured Spring SimpleMailMessage and this will be injected in the “MailService” class using “by name autowiring”.

In case you wish to use Gmail’s SMTP server, make sure that the following JavaMail properties are configured appropriately:


While in development phase, set “mail.debug” to true if you want the mail client to generate informative logs. However, remember to set this to false when in production, because the amount of logs could degrade the application’s performance and/or fill-up your hard disks.

Finally, we create a class that will be used to create the Spring container and test the simple mail service we created. The source code is the following:

package com.javacodegeeks.spring.mail;

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

public class MailServiceTest {

    public static void main(String[] args) {
        ApplicationContext context = new FileSystemXmlApplicationContext("conf/spring.xml");

        MailService mailService = (MailService) context.getBean("mailService");
        mailService.sendMail("[email protected]", "[email protected]", "Testing123", "Testing only \n\n Hello Spring Email Sender");
        mailService.sendAlertMail("Exception occurred");

The FileSystemXmlApplicationContext class is used as the ApplicationContext. We pass the Spring’s XML file location in the constructor and the class creates the container, instantiates the beans and takes care of the dependencies. Don’t you love Spring? Next, we retrieve a reference of our “MailService” service using the “getBean” method and invoke the two methods.

That’s all. As always, you can download the full Eclipse project from here.

Related Articles :

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area from our partners over at ZipRecruiter



  1. DEBUG: JavaMail version 1.4.3DEBUG: successfully loaded resource: /META-INF/javamail.default.providersDEBUG: Tables of loaded providersDEBUG: 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.mapDEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]DEBUG SMTP: useEhlo true, useAuth trueDEBUG SMTP: trying to connect to host “EXCHINDMAIL.xyzcompany.com”, port 25, isSSL falseDEBUG SMTP: exception reading response: java.net.SocketException: Connection resetException in thread “main” org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Exception reading response;  nested exception is: java.net.SocketException: Connection reset at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:418) at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:307) at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:297) at com.javacodegeeks.spring.mail.MailService.sendMail(MailService.java:24) at com.javacodegeeks.spring.mail.MailServiceTest.main(MailServiceTest.java:14)Caused by: javax.mail.MessagingException: Exception reading response;  nested exception is: java.net.SocketException: Connection reset at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1925) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1684) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525) at javax.mail.Service.connect(Service.java:291) at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:388) … 4 moreCaused by: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(Unknown Source) at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:106) at java.io.BufferedInputStream.fill(Unknown Source) at java.io.BufferedInputStream.read(Unknown Source) at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:84) at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1903) … 8 moreiam getting the above Exception, when i tried to run the code ……….
    Please help me…

  2. Hi is it possible to do same scenario in spring mvc project to send password expired alert notification to mail id that we saved in user table after 30 days.please help me how to follow the steps ,i have a requirement in my application ,i am using spring mvc,spring security and jpa.

    thanks in advance

  3. Hey nice tutorial….
    its working fine with me
    But i have to take the senders mail ids from the jsp page so how can i put those mail ids in springs xml file????
    Thanks in advance

  4. Spring actually not needed,

    here is an example, use in every project and enjoy java mail.

    public void sendMessage(String messageTo, String messageCc, String messageBcc, String subject, String plainBody, String htmlBody)
    throws MessagingException {

    Properties props = new Properties();
    props.put(“mail.smtp.host”, “smtp.gmail.com”);
    props.put(“mail.smtp.socketFactory.port”, “465”);
    props.put(“mail.smtp.auth”, “true”);
    props.put(“mail.smtp.port”, “465”);

    Session session = Session.getInstance(props,
    new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(“[email protected]”, “very secret password”);

    MimeMessage message = new MimeMessage(session);

    boolean parseStrict = false;
    // set from whom message is
    message.setFrom(new InternetAddress(“[email protected]”));
    // set recipients of message
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(messageTo, parseStrict));
    // set cc
    if (messageCc != null && messageCc.length() > 0) {
    message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(messageCc, parseStrict));
    // set bcc
    if (messageBcc != null && messageBcc.length() > 0) {
    message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(messageBcc, parseStrict));

    try {
    message.setSentDate(new Date());
    Multipart multiPart = new MimeMultipart(“alternative”);
    message.setSentDate(new Date());
    BodyPart plainBodyPart = new MimeBodyPart();
    plainBodyPart.setHeader(“Content-Type”, “text/plain; charset=UTF-8”);
    plainBodyPart.setHeader(“Content-Transfer-Encoding”, “8bit”);

    MimeBodyPart htmlBodyPart = new MimeBodyPart();
    htmlBodyPart.setText(htmlBody, “UTF-8”);
    htmlBodyPart.setHeader(“Content-Type”, “text/html; charset=UTF-8”);
    htmlBodyPart.setHeader(“Content-Transfer-Encoding”, “8bit”);


    message.setContent(multiPart, “UTF-8”);

    message.setHeader(“X-Mailer”, “X-Mailer”);
    message.setHeader(“Content-Transfer-Encoding”, “quoted-printable”);
    message.setSubject(subject, “UTF-8”);
    } catch (Exception e) {
    LOG.error(“Error during sending the mail ” + e);

  5. hi,, i’ve try there is no errors , but when i insert my gmail and my gmail pass, there is nothing email come to my email .. can you help me ?

    – thanks

  6. hii i’m newbie in java, now i learn about java spring mvc .. and , i’ve success doin this tutorial, thanks :) ,
    but now how to convert this to spring mvc framework ?
    because i’ve try and not work :( , i hope you can help me

  7. Hi ,
    I am doing the same, I am able to send mail to specified email id successfully but not able to see the SUBEJCT in mail and also not able to see the TO id. can you please help me out.

  8. Thanks this is great tutorial. It will be great to get such a tutorial for reading emails and downloading attached files :).

  9. how to run this code in eclipse , after downloading

  10. email sent but not recieved.. please help

Leave a Reply

Your email address will not be published. Required fields are marked *


Want to take your Java skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • Spring Interview QnA
  • Multithreading & Concurrency QnA
  • JPA Minibook
  • JVM Troubleshooting Guide
  • Advanced Java
  • Java Interview QnA
  • Java Design Patterns