Advertisement



< Prev



Spring Framework with Java Mail



In this tutorial, we will explain how to configure Spring Framework with Java Mail in order to send e-mail from one e-mail address to another.
In general, we could send two types of an e-mail -
Spring Framework provides the support for sending both simple text e-mail messages and MIME e-mail messages through its class - JavaMailSenderImpl.

The JavaMailSenderImpl class uses SimpleMailMessage class(also provided by Spring Framework) class to send a text message. The JavaMailSenderImpl class uses MimeMessageHelper class to send MIME type e-mail message.

The JavaMailSenderImpl also provide support to provide information about the host, username, password, port, protocol and mail properties which allows us to send either types of e-mail messages.




Creating the Java class - MailSender


We are going to create a Java class named MailSender within the decodejava package and this class is going to contain a few properties, such as - We are also going to define a couple of setter methods for these properties. These properties will be assigned a value by the Spring Container when a MailSender bean is created by it using the configuration xml file(to be created in the upcoming section).


package decodejava;


import java.io.File;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;


public class MailSender 
{
	private SimpleMailMessage simpleMailMessage;
	private JavaMailSenderImpl javaMailSenderImpl;
	
	
	//Setting the SimpleMailMessage property
	public void setSimpleMailMessage(SimpleMailMessage smm)
	{
		simpleMailMessage = smm; 
	}

	
	//Setting the JavaMailSenderImpl property
	public void setJavaMailSenderImpl(JavaMailSenderImpl jms)
	{
		javaMailSenderImpl = jms;
		
	}
	
	
	//Sending a text mail message
	public void sendTextMail()
	{
		javaMailSenderImpl.send(simpleMailMessage);
	}

	
	
	
	//Sending a MIME mail message
	public void sendMimeMail(String from, String to, String subject, String body, String fileName, String location) throws MessagingException
	{
		MimeMessage mimeMsg = javaMailSenderImpl.createMimeMessage();
		MimeMessageHelper mimeMsgHelper = new MimeMessageHelper(mimeMsg, true);
		mimeMsgHelper.setFrom(from);	
		mimeMsgHelper.setTo(to);
		mimeMsgHelper.setSubject(subject);
		mimeMsgHelper.setText(body);
		mimeMsgHelper.addAttachment(fileName, new File(location));	
		javaMailSenderImpl.send(mimeMsg);
	}
}

Besides the setter methods, this class is also providing two more methods -


Advertisement




Adding the Utility class that calls the Spring API


Next, we are going to create another class named - Utility, which is a simple java class.

Utility.java
package decodejava;


import java.util.Set;
import java.util.TreeSet;

import javax.mail.MessagingException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class Utility {

	public static void main(String[] args) throws MessagingException 
	{
		ApplicationContext context = new FileSystemXmlApplicationContext("classpath:config.beans.xml");
		MailSender sender = context.getBean("mailSenderBean",MailSender.class);
		
		//Sending a simple text email message
		sender.sendTextMail();
		
		System.out.println("Simple text email sent successfully!");
		
		
		String from = "sender-email-address@abcd.com";
		String to = "recipient-email-address@abcd.com";
		String subject = "Hello";
		String body = "Have a good day!";
		String fileName = "Sending a picture";
		String location = "D:\\IMG_2415.jpg";
		
		//Sending a MIME email message
		sender.sendMimeMail(from, to, subject, body, fileName, location);
		
		System.out.println("MIME email with attachment sent successfully!");
	}

}



The Utility class uses the ApplicationContext container(an interface) of Spring Framework by creating its instance using its implemented class FileSystemXmlApplicationContext, which loads the configuration xml file - config.beans.xml and creates MailSender bean.

While creating the MailSender bean, the setter methods. i.e. setSimpleMailMessage(), setJavaMailSenderImpl() are automatically called.

The simple text message is sent by calling sendTextMail() method and MIME type email message is sent by calling sendMimeMail() method of MailSender class.




Adding a configuration file


Next, we are going to add a configuration file to our project. This configuration document is an Extensible Markup Language(XML) file, ending with .xml extension and we are going to name file as config.beans.xml.

In this file, we have configured a MailSender bean with a unique id and have also configured its two properties, such as - SimpleMailMessage and JavaMailSenderImpl.


config.beans.xml
<?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:util="springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/context/spring-context.xsd
       ">
           
<bean id="mailSenderBean" class="decodejava.MailSender">
	<property name="simpleMailMessage" ref = "simpleMailMessageBean"/>
	<property name="javaMailSenderImpl" ref = "javaMailSenderImplBean"/>
</bean>



<bean id="simpleMailMessageBean" class="org.springframework.mail.SimpleMailMessage">
		<property name="from" value="sender-@email-address.com"></property>
		<property name="to" value="recipient@email-address.com"></property>
		<property name="subject" value="Hello"></property>
		<property name="text" value="Have a good day!"></property>
</bean>


<bean id="javaMailSenderImplBean" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host" value="smtp.zoho.com"></property>
		<property name="username" value="sender-email-address@abcd.com"></property>
		<property name="password" value="enter-your-password-here"></property>
		<property name="port" value="587"/> 
		<property name="protocol" value="smtp"/>
		
		
		<property name="javaMailProperties">
	  	   <props>
		          <prop key="mail.smtp.auth">true</prop>
			  <prop key="mail.smtp.starttls.enable">true</prop>
		   </props>
		</property>
</bean>

</beans>



This mapping document has a parent <beans> tag as the root element and its individual child elements, each with a <bean> tag, containing all the attributes such as -

The ref property "simpleMailMessageBean" refers to a SimpleMailMessage bean with id having a similar value "simpleMailMessageBean", declared in this configuration file, to initiate SimpleMailMessage object.




The ref property "javaMailSenderImplBean" refers to a JavaMailSenderImpl bean with id having a similar value "javaMailSenderImplBean", declared in this configuration file, to initiate SimpleMailMessage object.

  • The javaMailProperties property specifies the important java mail properties such as whether we are going to use a tls or ssl protocol to send the email.





  • Adding JARs


    • We are going to add some JARs files to our Java project. These JARs are required in order to successfully execute a Spring project.

      All these JARs are included in the folder named libs(within our Spring installation folder). So, we need to add all the JARs in the libs folder to our build path of our Java project.

      Note : Those who don't know how to add JARs to the build path of your Java project in Eclipse IDE, please refer to our section Adding JARs to your Spring project in Eclipse.






    Directory Structure of Project




    The picture above depicts how and where to arrange classes and interfaces comprising this Spring Project, in a specific directory structure.

    Project Folder - SpELWithJavaMail is the name of our Project and it is a top-level directory.






    Execution


    Finally, after executing Utility class, you will get the following output within the Console window. This output shown below, shows how the Utility class has used the ApplicationContext container of Spring Framework to load the configuration xml file - config.beans.xml, access the beans specified in it, instantiates MaiSender bean by calling its respective setter methods.

    Using the created bean of MailSender class, the simple text message is sent by calling sendTextMail() method and MIME type email message is sent by calling sendMimeMail() method of MailSender class.

    Aug 27, 2018 6:48:54 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@1c4af82c: startup date [Mon Aug 27 18:48:54 2018]; root of context hierarchy
    Aug 27, 2018 6:48:54 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from class path resource [config.beans.xml]
    Simple text email sent successfully!
    MIME email with attachment sent successfully!


    This concludes how to configure the Spring Framework with Java Mail to send e-mails from source to destination.




    Please share this article -




    < Prev
    < SpEL with XML



    Advertisement

    Please Subscribe

    Please subscribe to our social media channels for daily updates.


    Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




    Advertisement



    Notifications



    Please check our latest addition

    C#, PYTHON and DJANGO


    Advertisement