Overview
This post will show you how to send email using Spring with example.

Sending e-mail from an application has become a very common and necessary functionality nowadays.

There are various events which require an e-mail notification to be sent to a user such as new account creation, contact update, password change, money transfer activity, credit card transaction notification, promotional mails etc.

With Spring being heavily used in present day applications, it is pretty convenient if the mails are sent using Spring only.
Luckily Spring provides a feature to send e-mail which prevents the developer from using external libraries in the application in order to have this functionality.
Dependencies

For sending mail from Spring framework, the application should have following 2 dependencies

  1. Spring framework.
  2. Java Mail api

Maven and Gradle dependencies for both the above are given below.

Maven

<dependency>
<groupId>javax.mail</groupId>
   <artifactId>javax.mail-api</artifactId>
   <version>1.5.1</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>5.2.5.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-beans</artifactId>
   <version>5.2.5.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>5.2.5.RELEASE</version>
</dependency>

Gradle

compile group: ‘javax.mail’, name: ‘javax.mail-api’, version: ‘1.5.1’
compile group: ‘org.springframework’, name: ‘spring-core’, version: ‘5.2.5.RELEASE’
compile group: ‘org.springframework’, name: ‘spring-beans’, version: ‘5.2.5.RELEASE’
compile group: ‘org.springframework’, name: ‘spring-context’, version: ‘5.2.5.RELEASE’

Sending Mail Using Spring

In real world, 2 basic entities are required for sending an e-mail :
A mail sender and a mail message.

1. Mail Sender
represents an entity which processes the message and provides a mechanism to send the message.
This object should have information such as mail server address, port, protocol, mail sender account credentials(user name and password) and other security settings.

Relating it to Spring framework, a mail sender object is represented by its core interface MailSender from package org.springframework.mail.MailSender.
This interface has a method send which takes a org.springframework.mail.SimpleMailMessage object as argument.

2. Mail message
represents the e-mail which needs to be sent. It should have attributes such as mail subject, message body, sender/receiver e-mail ids.

In Spring framework, a mail message is represented by an object of org.springframework.mail.SimpleMailMessage or org.springframework.javamail.MIMEMessagePreparator.
These classes have properties like e-mail ids of sender and receiver, subject of message, message body etc.

Thus for sending e-mail using Spring framework, one needs to configure and populate objects of org.springframework.mail.MailSender and org.springframework.mail.SimpleMailMessage or org.springframework.javamail.MIMEMessagePreparator.

These are explained below stepwise.

MIMEMessagePreparator is required for sending MIME Messages. For basic e-mails, SimpleMailMessage is sufficient.

How to create object of MailSender
MailSender is an interface with JavaMailSenderImpl as its implementation.
Thus we need to create an object of this class and supply the values of necessary properties.
This class can be configured as a bean in Spring configuration file as below:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.codippa" />
<mvc:annotation-driven />

 <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="[your server host]" />
        <property name="port" value="[your port]" />
        <property name="username" value="[email id of the user]" />
        <property name="password" value="[email id password]" />
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.transport.protocol">smtp</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
                <prop key="mail.debug">true</prop>
            </props>
        </property>
    </bean>

</beans>

Once the bean is declared in configuration file, its instance can be retrieved in the code by injecting it in a field of type MailSender or by getting it from ApplicationConext using bean id.
Mail can be sent using its send method which takes an object of SimpleMailMessage as argument. |

Configuring SimpleMailMessage is explained next.

How to create object of Mail Message
An object of type org.springframework.mail.SimpleMailMessage can be created using its default constructor.
It provides setter methods to set various properties such as the sender and receiver e-mail ids, mail subject and message body.

Joining things together : Sending Mail
Once we have configured mail sender and mail message objects, they can be easily integrated to send mail which is shown in the code below.

package com.codippa;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

public class MailSenderTest {

   public static void main(String[] args) {
      ApplicationContext context = new FileSystemXmlApplicationContext("context.xml");
      //get JavaMailSenderImpl object from application context
      MailSender mailSender = (JavaMailSenderImpl)context.getBean("mailSender");
      //create and populate object of the message to be sent
      SimpleMailMessage message = new SimpleMailMessage();
      message.setFrom("connect@codippa.com");
      message.setSubject("Test mail Spring");
      message.setTo("codippa@gmail.com");
      mailSender.send(message);
   }
}

Alternate Method

The above approach directly gets the instance of org.springframework.mail.MailSenderbean defined in configuration file using ApplicationContext and calls its send method to send the e-mail.
There is another method which initializes the instance of MailSender using Spring’s dependency injection capabilities.

In this method the mail sending logic is moved to another class, say com.codippa.SendMailService.
This class contains org.springframework.mail.MailSenderas a field which is initialized by Spring automatically.

Both org.springframework.mail.MailSenderand SendMailService are declared as a bean in configuration file as shown below.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

<context:component-scan base-package="com.codippa" />

<mvc:annotation-driven />

  <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
   <property name="host" value="[your server host]" />
   <property name="port" value="[your port]" />
   <property name="username" value="[email id of the user]" />
   <property name="password" value="[email id password]" />
   <property name="javaMailProperties">
      <props>
         <prop key="mail.smtp.auth">true</prop>
         <prop key="mail.transport.protocol">smtp</prop>
         <prop key="mail.smtp.starttls.enable">true</prop>
         <prop key="mail.debug">true</prop>
      </props>
   </property>
  </bean>
  <!-- Declare your own class as a bean and inject Spring's mail sender into its property -->
  <bean id="sendMailService" class="com.codippa.SendMailService">
     <property name="mailSender" ref="mailSender"/>
   </bean>

</beans>

 

Our own class code is as below:

package com.codippa;

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

public class SendMailService {

   private MailSender mailSender;
   
   /**
    * Setter method for dependency injection
    */
   public void setMailSender(MailSender mailSender){
      this.mailSender = mailSender
   }
   
   public void sendMail() {
     //create and populate object of the message to be sent
     SimpleMailMessage message = new SimpleMailMessage();
     message.setFrom("connect@codippa.com");
     message.setSubject("Test mail Spring");
     message.setTo("codippa@gmail.com");
     // send mail 
     mailSender.send(message);
   }
}

Now write a main class which will get an instance of com.codippa.SendMailService and call its mail sending method.

package com.codippa;

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

public class MailSenderTest {

   public static void main(String[] args) {
      ApplicationContext context = new FileSystemXmlApplicationContext("context.xml");
      //get the instance of your class from application context
      SendMailService mailSenderService = (SendMailService)context.getBean("sendMailService");
      //call send method of your service class
      mailSenderService.sendMail();
   }
}

Let’s tweak in

  1. If you want to send an attachment along with the mail, use an object of type org.springframework.javamail.MIMEMessagePreparator
  2. @Autowired annotation can be applied over MailSender in class com.codippa.SendMailService in order to initialize it.
    In that case, there is no need for its setter method. This is known as Autowiring in Spring.

0

Leave a Reply

Mark Your Impression

  Subscribe  
Notify of
Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.