Chapter 7. Integrating JavaMail and JMS with Spring

In this chapter, first, we will go through the e-mail support in Spring to develop an e-mail application. We will then look into the JavaMail API and the Spring API for e-mails. Later in this chapter, you will learn to develop a simple Spring e-mail application.

In an e-mail application, an e-mail composed by a client is sent to a server and then delivered to the destination and then sends back a response to the client. Here, the communication between the client and the server is completely synchronous, which can be enriched by making this communication asynchronous. The Java messaging system is the standard application programming interface (API) to perform asynchronous communication.

Secondly, we will cover JMS and what message and messaging is. Then, we will look into the JMS application and its components. We will also cover MOM Service Provider and the configuration of ActiveMQ as Message Queue. Then, we will configure a Spring bean in the Spring configuration file, and using Spring JMS template, we will create a MessageSender class and run an application to perform a functionality related to JMS.

The list of the topics covered in this chapter is as follows:

  • E-mail support in Spring
  • Spring Java Messaging Service

E-mail support in Spring

Electronic mail (e-mail) plays an important role in all day-to-day activities in this era of global networks. Suppose you want to get periodic updates of a particular feature on a website, by just subscribing to that feature, you will start receiving e-mails regarding these updates. E-mails also allow you to send notifications, business orders, or any periodic reports of a producer.

Oracle provides a simple yet powerful API known as a JavaMail API for creating an application with an e-mail support. The JavaMail API provides a set of classes and interfaces for creating an e-mail application. This API is used to programmatically send and receive e-mails, which can be scaled up to work with different protocols associated with the mailing system. Although it is a powerful API, it is very complex, and using the JavaMail API directly in our application is a slightly tedious task as it involves writing a lot of code.

The Spring Framework provides a simplified API and plugging for a full e-mail support, which minimizes the effect of the underlying mailing system specifications. The Spring e-mail support provides an abstract, easy, and implementation-independent API for sending e-mails. In this chapter, we will get an overview on the JavaMail API and learn how to send e-mail using the JavaMail API in Spring.

Introducing the JavaMail API

The JavaMail API provides a protocol-independent and platform-independent framework to provide e-mail support for a Java application. The JavaMail API is a collection of classes and interfaces that comprise an e-mail system. The steps involved in sending a simple e-mail using the JavaMail API are as follows:

  1. Connect to an e-mail server by specifying the username and password; let's say for example, if you want to send an e-mail from [email protected], then you need to connect to the e-mail server of xyz.com.
  2. Create a message by specifying the recipient's addresses that can include Cc and Bcc addresses as well.
  3. Add attachments to the message if any.
  4. Transport the message to the e-mail server.

Sending a simple e-mail requires the use of a number of classes and interfaces that are present in the javax.mail and javax.mail.internet packages. The important classes and interfaces in the JavaMail API are listed in the following table:

Class/interface

Description

Session

The javax.mail.Session is the key class of the JavaMail API. It represents an e-mail session. Typically, we create a Session object, set the properties, and send a message.

Message

The javax.mail.Message is an abstract class of the JavaMail API that models an e-mail message. It represents the e-mail sent.

Transport

The javax.mail.Transport is an abstract class of the JavaMail API that represents the protocol used to send and receive e-mails. The Transport object is used for sending an e-mail message.

Authenticator

The javax.mail.Authenticator is an abstract class of the JavaMail API that represents an authentication for the e-mail provider.

PasswordAuthentication

The PasswordAuthentication holds the username and password by the Authenticator object.

MimeMessage

The javax.mail.internet.MimeMessage is an abstract class that represents a Multipurpose Internet Mail Extension (MIME) message. MimeMessage is an e-mail message, which will understand the MIME types and headers.

InternetAddress

The javax.mail.internet.InternetAddress represents an Internet e-mail address such as To, Bcc, and Cc.

The JavaMail application uses the JavaMail API to exchange e-mails, as shown in the following figure:

Introducing the JavaMail API

Using the JavaMail API

The JavaMail API can be used to create a class to send an e-mail using the MailHelper class. This MailHelper class contains a constructor, which can be used to initialize the host, username, and password. This MailHelper class also contains the sendMail() method.

The following code snippet shows the MailHelper.java class:

public class MailHelper {

   private Properties props;
   private String host;
   private String userName;
   private String password;

   public MailHelper(String host, String username, String password){
          this.userName = username;
          this.password = password;
          props = new Properties();
          // put host information
          props.put("mail.stmp.host", host);
          // put true for authentication mechanism
          props.put("mail.smtp.auth", "true");
   }

   public void sendMail(String from, String to, String subject, String body){
          Session session = Session.getDefaultInstance(props, new PasswordAuthenticator());
          try{
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(from));
                InternetAddress toAddress = new InternetAddress(to);
                message.addRecipient(RecipientType.TO, toAddress);
                message.setSub(subject);
                message.setText(body);
                Transport transport = session.getTransport("smtp");
                transport.connect();
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
          } catch(NoSuchProviderException ex){
                ex.printStackTrace();
          } catch(MessagingException ex){
                ex.printStackTrace();
          }
   }

   private class PasswordAuthenticator extend Authenticator{
          protected PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication(userName, password);
          }
   }
}

In the preceding code snippet, the MailHelper class has instance variables and a constructor. The props variable, of the Properties collection type, used to specify the common properties to connect to the e-mail provider host.

Simple Mail Transfer Protocol (SMTP) is a protocol that is used to send e-mails. The SMTP server performs this job. The props.put("mail.stmp.host", host) code inside the constructor is used to specify the host information, where we connect to the SMTP server of our host. The props.put("mail.smtp.auth", "true") code inside the constructor specifies the use of an authentication mechanism to connect to the SMTP server.

The sendMail method of the MailHelper class creates a Session object using the host information and the username-password credentials. The from-address and the to-address are added to the instance of the MimeMessage class. The subject and the body of the e-mail are also added to this MimeMessage object. Finally, the message is sent using an instance of the Transport class.

The PasswordAuthenticator class is an inner class that has been used by a Session object to hold the username and the password.

From the preceding code, the following problems can be encountered:

  • Lots of initialization and creation work involved in sending a simple e-mail
  • Exceptions need to be taken care of while using the JavaMail API; this results in some extra lines of code
  • Some extra classes are needed if required to perform the attachment operation while sending an e-mail using the JavaMail API
  • A solution to the preceding problem is provided by the Spring Framework that simplifies the use of the JavaMail API to send e-mails

Let's understand the use of the Spring API for the JavaMail API and rewrite the MailHelper class.

The Spring API for JavaMail

The Spring Framework provides an API to simplify the use of the JavaMail API. The classes handle the initialization, clean-up operations, and exceptions. The packages for the JavaMail API provided by the Spring Framework are listed in the following table:

Package

Description

org.springframework.mail

This defines the basic set of classes and interfaces for sending e-mails

org.springframework.mail.java

This defines JavaMail API-specific classes and interfaces for sending e-mails

In the Spring mail API hierarchy, the org.springframework.mail package is the root-level package for the Spring Framework's e-mail support, as shown here:

The Spring API for JavaMail

The important classes and interfaces in the org.springframework.mail package are listed in the following table:

Class/interface

Description

MailMessage

Refers to a common interface for all types of messages that can be sent. It doesn't support complex MIME messages. It is used for sending simple plain-text e-mails.

MailSender

Refers to an interface that defines methods for sending simple e-mails. It supports only the plain-text e-mails.

MailException

Refers to a base class for all the exceptions thrown by the mailing system.

SimpleMailMessage

Refers to the class that defines the representation of a simple message that can be sent.

The important classes and interfaces in the org.springframework.mail.java package are listed in the following table:

Class/interface

Description

JavaMailSenderImpl

Refers to the implementation of the JavaMailSender interface. It is a core class that is used to send simple as well as MIME messages. It extends the MailSender interface and provides the methods for constructing and sending a MIME message.

MimeMailMessage

Implements the MailMessage interface. It is based on the JavaMail MIME message.

MimeMessageHelper

Acts as a wrapper for a MIME message. It is used to populate a MIME message and is used by the JavaMailSenderImpl class.

The Java application can use Spring to access the JavaMail API for sending e-mails, as shown in the following figure:

The Spring API for JavaMail

In the preceding figure, the Java classes use the Spring API, which indirectly uses the JavaMail API to send e-mails.

Developing a Spring Mail Application

Let's create a JavaMail API with the Spring application for sending e-mails via the Gmail SMTP server using the Spring mail API. Here, we develop a basic e-mail application that creates simple e-mails containing text only.

Configuration file – Spring.xml

Let's now create the configuration file, Spring.xml, and configure the mailSender bean of the JavaMailSenderImpl class and define its properties:

  • host
  • port
  • username
  • password

Also, configure the bean for the EmailService class with the mailSender property:

<!-- SET default mail properties -->
<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="username" />
   <property name="password" value="password" />
 
   <property name="javaMailProperties">
      <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
             </props>
   </property>
</bean>

<bean id="emailService" class="org.packt.Spring.chapter10.mail">  
    <property name="mailSender" ref="mailSender" />  
</bean>

The preceding configuration file sets the host as "smtp.gmail.com" and the port as "25." The username and the password properties need to be set with reader's username and password of their Gmail account. The username is used as the sender of the e-mail.

Spring's e-mail sender

It is the e-mail API-specific Java file. It provides the definition of the sendEmail() method, which is used to send the actual e-mail to the recipient:

package org.packt.Spring.chapter10.mail;

import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
 
public class EmailService
{

   @Autowired
   private MailSender mailSender;
 
   public void sendEmail(String to, String subject, String msg) {
 
          // creates a simple e-mail object
          SimpleMailMessage email = new SimpleMailMessage();
 
          email.setTo(to);
          email.setSubject(subject);
          email.setText(msg);

          // sends the e-mail
          mailSender.send(email);
   }
}

Here, we have autowired MailSender and called the send() method that will send the e-mails.

The MailerTest class

The MailerTest class has the main() method that will call the sendEmail() method of the EmailService class and send an e-mail:

package org.packt.Spring.chapter10.mail;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class MailerTest
{
    public static void main( String[] args )
    {
         //Create the application context
         ApplicationContext context = 
             new ClassPathXmlApplicationContext("Spring.xml");
 
      //Get the mailer instance
       EmailService emailService = (EmailService)context.getBean("emailService ");

        //Send a composed mail
        emailService.sendEmail("****@gmail.com",
                   "Email Test Subject", 
                   "Email Testing body");
 
    }
}

The output of this application can be confirmed by opening the inbox.

We have developed an application using Spring e-mails. Let's now understand the Spring Java Messaging Service.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.201.93