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:
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.
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:
[email protected]
, then you need to connect to the e-mail server of xyz.com
.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:
The JavaMail application uses the JavaMail API to exchange e-mails, as shown in the following figure:
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:
Let's understand the use of the Spring API for the JavaMail API and rewrite the MailHelper
class.
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 |
---|---|
|
This defines the basic set of classes and interfaces for sending e-mails |
|
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 important classes and interfaces in the org.springframework.mail
package are listed in the following table:
The important classes and interfaces in the org.springframework.mail.java
package are listed in the following table:
The Java application can use Spring to access the JavaMail API for sending e-mails, as shown in the following figure:
In the preceding figure, the Java classes use the Spring API, which indirectly uses the JavaMail API to send e-mails.
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.
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.
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 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.
18.216.201.93