Spring Java Mail – Integration of Spring with Java Mail

Job-ready Online Courses: Click, Learn, Succeed, Start Now!

1. Spring Java Mail – Objective

In our last Spring Framework tutorial, we studied Spring Expression Language Operators. Here, in this Spring Java Mail Tutorial, we will discuss Integration of Spring with Java Mail. Moreover, we will learn the Java Mail API and how to send Spring mail using Gmail Server with an example.
So, let’s start Spring Java Mail Tutorial.

Spring Java Mail

Spring Java Mail – Integration of Spring with Java Mail

2. Integration of Spring with Java Mail

In this Spring Java Mail article, you will learn about another Spring integration with Java Mail. This article will allow you to send and receive emails using the Spring Framework interfaces and classes. You will be using Java Mail API for sending and receiving the mail. For more understanding, you will see a working example with Eclipse IDE in place.
Do you know about the Spring Bean Life Cycle – Initialization and Destruction

3. Java Mail API

Spring Java Mail

Java Mail API

Spring Framework has many user interfaces and classes for sending/receiving your emails. There is a package called org.springframework.mail. It is a root package which provides the mail support in the Spring Framework.
The classes and interfaces required for java mail support in Spring Framework are defined as follows:

Spring Java Mail – API

a. MailSender Interface

It is a root interface which provides basic functionality for sending the simple mails.

b. JavaMailSender Interface

It is sub-interface of MailSender. It supports MIME messages and is used with MimeMessageHelper class. It is used for creating JavaMail MimeMessage. MimeMrssagePreparator mechanism is recommended for the use of this interface.
Follow this link to know about Spring WS Integration

c. JavaMailSenderImpl Class

It has the implementation of the JavaMailSender interface and supports JavaMail Mime Messages and the Spring Simple Mail Messages.

d. SimpleMailMessage Class

It provides help in creating a simple mail message including from, to, cc, subject etc.

e. MimeMessagePreparator Interface

It is used as call back interface for preparing the JavaMail MIME messages.

f. MimeMessageHelper Class

It is used as a helper class which contains MIME message and offers support for inline elements like HTML text content, images etc.

4. Example of Sending Mail in Spring using Gmail Server

In this example you will see two Spring Mail classes:

  • SimpleMailMessage for creating messages.
  • JavaMailSenderImple for sending the messages.

Following files are needed for sending the email using Spring Framework:

  • MailMail.java
  • ApplicationContext.java
  • Test.java
Spring Java Mail

Spring Java Mail Tutorial – Example of Sending Mail in Spring using Gmail Server

Before you start you need to have mail.jar and activation.jar for running this example.

a. MailMail.java

package com.example;  
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);     
     }  
 }

It is the simple class which is used for defining mailSender property and the object of MailSender will be provided to this property during the runtime. The send() of MailSender interface is used for sending simple mail.
Let’s explore Spring MVC Tiles 3 Integration in detail

b. ApplicationContext.xml

In this XML file, you will create a bean for JavaMailSenderImpl class. You need to define the values of the below properties:

  • Host
  • Username
  • Password
  • JavaMailProperties
<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">   
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">  
  <property name="host" value="smtp.gmail.com" />  
    <property name="username" value="[email protected]" />  
    <property name="password" value="yourgmailpassword" />  
    <property name="javaMailProperties">  
       <props>  
              <prop key="mail.smtp.auth">true</prop>  
              <prop key="mail.smtp.socketFactory.port">465</prop>  
              <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>  
              <prop key="mail.smtp.port">465</prop>  
        </props>  
    </property>  
</bean>  
<bean id="mailMail" class="com.example.MailMail">  
    <property name="mailSender" ref="mailSender" />  
</bean>  
</beans>
Spring Java Mail

Example of Sending Mail in Spring using Gmail Server

c.Test.java

This class gets the bean of email mail from the applicationContext.xml file and calls the sendmail method of MailMail class.

package com.example;  
import org.springframework.beans.factory.*;  
import org.springframework.beans.factory.xml.XmlBeanFactory;  
import org.springframework.core.io.*;  
public class Test {   
      public static void main(String[] args) {     
      Resource r=new ClassPathResource("applicationContext.xml");  
      BeanFactory b=new XmlBeanFactory(r);  
      MailMail m=(MailMail)b.getBean("mailMail");  
      String sender="[email protected]";//write here sender gmail id  
      String receiver="[email protected]";//write here receiver id  
      m.sendMail(sender,receiver,"hi","welcome");  
      System.out.println("success");  
    }  
 }

Do you know about Spring AOP Tutorial
To run the example:

  • Load the Spring jar files for java mail.
  • Load the jar files mail.jar and activation.jar
  • Change the properties such as username and password in applicationContext.xml file.
  • Change sender gmail id and receivemail id in Test.java file.
  • Compile and run the Test class.

So, this was all about Spring Java Mail Tutorial. Hope you like our explanation.

5. Conclusion

Hence, in this session, you learned about the Spring integration with Mail API. You saw how Java Mail API is used for sending and receiving the mail. For more understanding, you saw a working example on how to configure mail and send/receive mails using Gmail server with Eclipse IDE in place. Still, you have any query, feel free to ask in the comment section.
Related Topic – Spring BeanPostProcessors
For reference

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

Leave a Reply

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