devxlogo

Send E-mail from a Web Form Using WebSphere Application Server and the JavaMail API

Send E-mail from a Web Form Using WebSphere Application Server and the JavaMail API

ending out email in a Web application is a common business need. In the Java realm, sending out e-mail is facilitated via the JavaMail API, which is a required part of the enterprise platform (Java EE) but can also be used with Java SE. JavaMail is a set of Java APIs that allow for the reading and sending of e-mail from within a Java application.

In this article, I’ll show you how to create a Java servlet housed in an enterprise application that sends out e-mail via the JavaMail API. My solution will utilize IBM WebSphere Application Server Version 6 and, for development, IBM Rational Application Developer Version 6 (hereafter called Application Developer). Application Developer is an Eclipse-based integrated development environment (IDE) that is ideally suited for use with WebSphere Application Server Version 6. The IDE has a built-in, single server test environment for WebSphere Application Server Version 6 (hereafter called WAS 6) that one can use to unit test their enterprise applications. In this article you’ll also learn some of the tooling in Application Developer that can help speed your WAS 6 development endeavors.

What You Need
Some basic familiarity with:

Finding Out Your SMTP Server Info
Before getting started, you need to find out what your organization’s SMTP server name and server port are. This can usually be found out by knocking on your system administrator’s door. Your SMTP server is usually something like SMTP.YOURCOMPANY.COM. The default SMTP port is 25. If you don’t have access to an SMTP server or if your system administrator doesn’t like you, then you can always run your own SMTP server. A popular, free program for running your own SMTP server is PostCast Server.

Configuring a Mail Provider
In order to send out an e-mail in a Java servlet, one could possibly create a mail session via a Properties object. However, on a J2EE server such as WAS 6, the recommended approach is to look up a Mail Session via the Java Naming and Directory Interface (JNDI). Accordingly, I’ll show you how to setup a Java Mail Session using the WAS 6 Administrative Console.

If you are using the built in WebSphere Application Server Test Environment, then you can fire up the Administrative Console from the Servers view by right-clicking to reveal the context menu and choosing “Run administrative console.” Otherwise, if you are using an external WebSphere Application Server environment, then just go to the administrative console using your Web browser. From the left-hand panel, choose Resources>Mail Providers (see Figure 1).

From the Mail Providers screen, click the Built-in Mail Provider. The Built-in Mail Provider of WAS 6 includes three protocol providers: Simple Mail Transfer Protocol (SMTP), Internet Message Access Protocol (IMAP) and Post Office Protocol (POP3). For sending out mail, I’ll be using the SMTP protocol provider of the built-in mail provider (see Figure 2).


Figure 1. Choose the Resources> Mail Providers option to begin creating a Mail Provider.
 
Figure 2. Select the Built-in Mail Provider as the mail provider.

In the subsequent Built-in Mail Provider configuration screen, click the “Mail sessions” link under the ‘Additional Properties’ area. Next, you need to create a Mail Session object. To begin creating the Mail Session object, click the New button (see Figure 3).

In the next screen, you need to define configuration information for your mail session. Specify a name of mymailsession. For a JNDI name, specify mail/mymailsession (see Figure 4).

Enter your SMTP server name for the “Mail transport host.” Make sure the Mail transport protocol is “smtp.” In some cases, an SMTP server restricts outgoing mail to authenticated users only. If this is the case with your server, additionally specify the authorized user ID and password recognized by your SMTP server on this dialog.


Figure 3. Click New to start creating a Mail Session.
 
Figure 4. Carefully configure your mail session on this dialog.

After you have specified your appropriate mail session configuration information, click the “Apply” button at the bottom of the configuration screen. You will be asked to “Click Save to apply changes to the master configuration.” Go ahead and do so and click Save again in the following screen to persist your administrative changes.

Flow Overview
Once you have configured your mail provider, you can roll up your sleeves and create the code to interact with it. For this solution you will create a Java Server Page (JSP) that interacts with a Java servlet. The Java servlet will be the workhorse that interacts with your mail provider. The JSP will send user data entered on a form to the servlet via a POST request. The Java servlet will then gather the form data and shoot off an e-mail message using the mail provider you configured earlier and the JavaMail API.

Creating Your Form JSP
Both the JSP and servlet are housed in the same Web module. Create both the JSP and servlet in a Dynamic Web Project in Application Developer. Name your Web project “JavaMailDemo” and house it in an EAR project named JavaMailDemoEAR with a context root of JavaMailDemo (see Figure 5).


Figure 5. Name your project JavaMailDemo and save it in an EAR file with a context root of the same name.
 
Figure 6. Right-click on the WebContent folder of your JavaMailDemo project and then insert a New JSP File using the context menu.

From the Web perspective in Application Developer, find the WebContent folder under the JavaMailDemo web project you just created. Right-click on it and select New>JSP File. Specify a file name of form and click Finish (see Figure 6).

Rational Application Developer has a Design view as well as a Palette, which can be used in tandem to build your JSP, incorporating the look and feel that you want. I suggest experimenting with the Design view some, which should give you the hang of using the drag-and-drop interface to manipulate the look and feel of your Web interface. You can also use the Source view to hand code and tweak your HTML source code. The downloadable source code for this article includes the JSP in the EAR file for this project. You can cut and paste the contents of the JSP file from the download into the Source view and save your changes.

The portion of the JSP that is of particular interest is the HTML form. When the form’s Submit button is clicked, a servlet named MailServlet is invoked. Data is passed to the servlet via a POST operation.

Name:
E-mail:
Message:

Note that the form.jsp file I provided does not have any Javascript validation in it to look for invalid e-mail address entries, blank entries, etc. Of course, in the real world, you would likely want to adopt such client-side validation checking.

The MailServlet Servlet
Now that you have your JSP file ready and waiting the next step is to create the servlet. Once again using the Web perspective within Rational Application Developer, expand the deployment descriptor icon under the JavaMailDemo project in the Project Explorer view. Under the deployment descriptor, you should see an option for Servlets. Right-click on the servlets icon and choose New>Servlet (see Figure 7).

Figure 7. Create a new servlet instance under the deployment descriptor in Application Developer.

In the subsequent Create Servlet wizard, name your servlet “MailServlet” and include it in a package named “com.devx.example.” This should create a Java class under the JavaResources>JavaSource>com.devx.example folder named MailServlet in the Project Explorer view. Click on the icon representing the class and modify the auto-generated doPost method as follows:

protected void doPost(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {    System.out.println("Entering MailServlet");    // extract parameters from HttpServletRequest object    String name = (String)request.getParameter("name");    String email = request.getParameter("email");    String messageBody = request.getParameter("message");    String subject = "Mail from MailServlet";    String destinationAddress = "[email protected]";     try     {        // look up MailSession        Context context = new InitialContext();Session mailSession = (Session)context.lookup("java:comp/env/mySession");        Message msg = new MimeMessage(mailSession);        msg.setFrom(new InternetAddress(email));        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destinationAddress));        // Set the subject and body text        msg.setSubject(subject);        msg.setText(messageBody);        // send message        Transport.send(msg);        System.out.println("Message Sent");        javax.servlet.RequestDispatcher dispatcher =         getServletContext().getRequestDispatcher("/sent.jsp");         dispatcher.forward(request,response);     }catch (NamingException e)     {        e.printStackTrace();        javax.servlet.RequestDispatcher dispatcher =             getServletContext().getRequestDispatcher("/error.jsp");         dispatcher.forward(request,response);     }catch (MessagingException e)    {        e.printStackTrace();        javax.servlet.RequestDispatcher dispatcher =         getServletContext().getRequestDispatcher("/error.jsp");         dispatcher.forward(request,response);    }    System.out.println("Exiting MailServlet");}

Before moving on I’ll dissect the servlet’s doPost method so you can understand it more thoroughly. The first thing the code does is grab the user-entered data from form.jsp and store the data in String variables. Then it populates a string (subject), which is used for the subject of the mail message, and then another string (destinationAddress), which establishes the e-mail address to which the mail messages will be sent.

Next, the creation of the javax.naming.InitialContext object creates a network connection to the directory service. The directory service looks up your javax.mail.Sessionobject, which you established earlier within the WebSphere Administration console. It is via this Session object that you can create your MimeMessage object with the call:

Message msg = new MimeMessage(mailSession);

Next, the from (sender) address, the recipient address, subject, and text of the message are set using the setter methods of the MimeMessage object. Finally, the message is sent out using the Transport object. If things go well, control of the Web browser is forwarded to a JSP named sent.jsp which informs the user that their message was sent.

There are a couple of exceptions that you have to catch in your servlet in case things go awry. Namely, javax.naming.NamingException (in case your JNDI lookup fails) and javax.mail.MessagingException(in case something goes wrong while you interact with the JavaMail API). In addition to printing out the stack trace to standard out, the servlet forwards the user to a JSP named error.jsp, which informs the user that an error occurred while sending the message.

Modifying Your Web Deployment Descriptor
If you have a discerning eye for observation, you may have noticed that in the servlet’s code, I look up the javax.mail.Session object with the name: java:comp/env/mySession. However, in the WebSphere Administrative Console, the name mail/mymailsessionwas used. This disparity is because I used a resource reference in the servlet code. A resource reference supports application access to a resource (such as a data source, URL, or in our case, a mail provider) using a logical name rather than the actual name in the runtime environment. This capability eliminates the necessity to alter application code when you change the resource runtime configurations.

To create the resource reference, open up the Web deployment descriptor and switch to the References tab (see Figure 8).


Figure 8. Use the References tab in the IDE to create the resource reference.
 
Figure 9. A wizard walks you through the process of creating a new resource reference.

Click the Add button to start creating your Reference. In the subsequent Add Reference wizard, choose the “Resource reference” when asked what type of reference you would like to create (see Figure 9).

In the screen that follows, specify a resource reference name of mySession. From the Type pull down, choose the object type of javax.mail.Session. For the Authentication Type choose Container and click Finish (see Figure 10).

When you are done, you should see the resource reference you just created in the References tab. In the WebSphere Bindings section, specify a JNDI name of mail/mymailsession. Be sure and click Ctrl-S to save your changes to the deployment descriptor (see Figure 11).


Figure 10. Name your new resource reference and give it an object type of javax.mail.Session.
 
Figure 11. Specify the name of your JNDI in the References tab.

Testing Things Out
To test out the completed application, all you have to do is right-click on the form.jsp artifact in the Project Explorer pane and choose the Run>Run on Server… option. After a short while, the WebSphere Application Server v6.0 test environment will fire up and you will be presented with the form.jsp in the Web browser. Go ahead and enter some test data as shown in Figure 12and click the Submit button. If everything is configured correctly, control will be passed off to the MailServlet servlet. This servlet will send out an email message using what was entered into form.jsp. When all is said and done, an email message should be received in the inbox of the recipient email address you specified in the servlet.

Figure 12. The completed form is a JSP page that will carry data to the servlet, which sends an email using the data you specify.

The JavaMail APIs provide a platform and protocol-independent framework for building Java-based mail client applications. JavaMail applications can connect to an SMTP server and send mail through it by using an SMTP protocol provider.

In a J2EE application server setting, such as WebSphere Application Server, rather than creating a javax.mail.Sessionobject using a properties object as you would normally do in a J2SE application, it is suggested that you obtain your Session object that was configured administratively as a resource in your application server. Using this methodology, your SMTP server setting information is decoupled from the code of your application.

One place where you might want to consider using such email functionality in your server-side code is when critical errors or exceptions are thrown. Rather than just logging your errors and exceptions, you can use the JavaMail API to send out and email to let an appropriate individual in your organization know to take appropriate, corrective actions.

Another example of where a one might leverage the JavaMail API on the application server is when there is a business need to have monthly statements sent out to customers. To do this, one could use an asynchronous bean to periodically (e.g., monthly) create reports (in the form of Excel or PDF) and send out email statements to customers using the JavaMail API. In particular, to facilitate this periodic creation, one might want to use Timer managers. Timer managers are asynchronous beans which implement the commonj.timers.TimerManagerinterface, which enable J2EE applications, including servlets and EJB applications to schedule future timer notifications and receive timer notifications. The Timer manager is an application-server supported alternative to using the J2SE java.util.Timer class, which is considered inappropriate for managed environments.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist