How to write a web application that sends email. The example uses the JavaMail feature for WebSphere Liberty.

I’m going to start by assuming that you’ve done the steps required to install and set up a server in Liberty. For this article, I’ve named my Liberty server mail.

The first thing we are going to do is update the mail’s server.xml to include the javaMail-1.5 feature, like so:

<?xml version="1.0" encoding="UTF-8"?>
<server description="new server">

    <!-- Enable features -->
    <featureManager>
        <feature>jsp-2.2</feature>
        <feature>javaMail-1.5</feature>
    </featureManager>

    <!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
    <httpEndpoint id="defaultHttpEndpoint"
                  httpPort="9080"
                  httpsPort="9443" />
</server>
  

This config will ensure that you’ve got access to the JavaMail API. If you are using a javax.mail.Session that is configured either ‘programmatically’ in the source, or using a MailSessionDefiinition or deployment descriptors, you are good to go (provided you also add the jndi-1.0 feature as well).

For this tutorial, I’m going to show you how to configure a <mailSession> in the server.xml. This is a Liberty-specific way to administer a javax.mail.Session, and lets us simply inject the session into our app with a JNDI lookup. If you’re going to be using any sort of work with JNDI (i.e. MailSessionDefinition annonnation, deployment descriptors, or the <mailSession>) you’ll need to add the <jndi-1.0> feature.

Here is an example of the way I configured it for my app:

<?xml version="1.0" encoding="UTF-8"?>
<server description="new server">

    <!-- Enable features -->
    <featureManager>
        <feature>jsp-2.2</feature>
        <feature>javaMail-1.5</feature>
        <feature>jndi-1.0</feature>
    </featureManager>

    <!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
    <httpEndpoint id="defaultHttpEndpoint"
                  httpPort="9080"
                  httpsPort="9443" />
				  
	<mailSession>
		<mailSessionID>gmailSMTPSession</mailSessionID>				
		<jndiName>ExampleMail/SMTPSender/gmailSMTPSession</jndiName>
		<description>My Gmail SMTP Session</description>
		<storeProtocol>imaps</storeProtocol>
		<transportProtocol>smtp</transportProtocol>
		<host>smtp.gmail.com</host>
		<user>youruseraccount@gmail.com</user>
		<password>yourpassword</password>
		<from>youruseraccount@gmail.com</from>
		<property name="mail.imap.host" value="imap.gmail.com" />
		<property name="mail.smtp.port" value="587" />
		<property name="mail.smtp.auth" value="true" />
		<property name="mail.smtp.starttls.enable" value="true" />
	</mailSession>

</server>
  

From this example you may or may not be able to tell that this one session is configured so that it can be used for both SMTP and IMAP on Gmail. However, for the purpose of this demo we are going to focus only only SMTP. Since Gmail has switched to OAuth authentication, I’ve had to go into my Google account settings and turn on the setting that allows less secure apps. Also, don’t forget to change <user>, <password>, <from> to match the ones for your account.

The last thing I’ll mention about the config is the <jndiName>, as you can see right now it’s ExampleMail/SMTPSender/GMAILSMTPSession, where ExampleMail is the name of the WAR file, SMTPSender is the class name, and gmailSMTPSession is, of course, the name of the actual session object. You can also use mail/gmailSMTPSession and that will be mapped to the default java:comp.

Below is the source for a simple Java EE web app I’ve written to send mail. So when I open the servlet address on the browser, it sends an email to my Gmail account using the mail Liberty server:

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;

@WebServlet("/SMTPSender")
public class SMTPSender extends HttpServlet{
	// Inject the javax.mail.Session created by in the server.xml
	@Resource(lookup="ExampleMail/SMTPSender/gmailSMTPSession")
	Session session;
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter(); 
		
		try {
		    
			Message message = new MimeMessage(session);
		
			message.setFrom(new InternetAddress("myacccount@gmail.com"));
		
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse("myaccount@gmail.com"));
			message.setText("Hey Thomas,nn"
					+ "Check it out, I've sent you a message compliments of the Liberty Profile"
					+ "nn Cheers! n"
					+ "Thomas");

			Transport.send(message);

			// If message is sent and no exceptions are thrown 
			// the servlet will print this message
			out.println("Message sent!");

		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (javax.mail.MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
	}
}

  

So after I got my WAR file built, I dropped the file in the the dropins folder in the {USER DIR}wlpusrserversmail directory. This is the response I get when I access the servlet address:


Sent

We got the confirmation message; now let’s check my Gmail account:


Recieve

So that’s what the message looks like in my Gmail inbox. And now you’ve seen how to write a basic web app using the javaMail-1.5 feature for Liberty.

Join The Discussion

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