Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

If you've ever wanted to create a Java application that could send out e-mail via a Web form, you need JavaMail in your toolbox. Find out how you can allow a simple JSP page to send out e-mail using IBM tools and the JavaMail API.




Application Security Testing: An Integral Part of DevOps

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.

<FORM action="/JavaMailDemo/MailServlet" method="post"> Name: <INPUT type="text" name="name" size="20"><BR> E-mail: <INPUT type="text" name="email" size="20"><BR> Message: <TEXTAREA rows="10" cols="20" name="message"></TEXTAREA> <BR> <BR> <INPUT type="submit" name="Submit" value="Submit"> </FORM>

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 = "youremailaddress@somewhere.com"; 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.Session object, 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/mymailsession was 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 12 and 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.Session object 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.TimerManager interface, 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.

Kulvir Singh Bhogal works as an IBM consultant, devising and implementing J2EE-centric solutions at customer sites across the nation.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date