The JavaTMMail API enables e-mail clients to send or receive e-mails from a mail server. The API provides a platform- and protocol-independent framework to build Java-based e-mail and messaging applications. The JavaMail API is implemented as an optional Java platform package and is also available as part of the Java 2 Platform, Enterprise Edition (J2EE).
This article focuses on building an application using the JavaMail API and unit testing the application in IBM ® WebSphere® Studio Application Developer (hereafter called Application Developer). It also provides information about a free e-mail server and a JavaMail scenario.
If you have experience using JavaMail 1.1 specifications, you would create a mail session using a Properties object. However, with JavaMail 1.2, it is better to look up the mail session through JNDI instead of creating a new one from properties. According to the WebSphere V5 InfoCenter, a mail session should always be looked up.
The J2EE specification considers a mail session instance as a resource, or a factory from which mail transport and store
connections can be obtained. Do not hard-code mail sessions, namely fill up a Properties object,
then use it to create a instance of the javax.mail.Session. (For more information, see
(WebSphere InfoCenter Version 5
-- Section Resources -- Using Mail).
Application Developer lets you use JavaMail without any special file setup. The only setup required is the actual mail session resource.
Application Developer does not provide a GUI interface for editing the mail provider and creating a mail session. Those two tasks have to be performed directly from the WebSphere Admin Console. This article will focus on sending e-mail in accordance with the JavaMail specifications.
Make sure you have an SMTP mail server available -- one is usually provided by the ISP through which you send e-mail. If you do not know of any mail server, you can install your own. A free mail server program that you can install is PostCast Server, which turns your machine into an outgoing SMTP mail server. You can use PostCast Server for this article instead of the SMTP server from your ISP.
Installing and configuring the PostCast SMTP mail server
- Download the installation image.
- Double-click the downloaded file, and the installation wizard should start.
- Click Next on the Welcome page.
- Accept the license agreement and click Next.
- Specify the installation location and click Next:

- Click Next again to start the installation.
- After the installation is complete (which may take awhile), click Finish to close the installation program.
The PostCast Server is now installed on your computer. However, it requires some configuration, which the following section will guide you through:
- From the Windows® Start menu, select Programs => PostCast Server => PostCast Server to start the Setup Wizard. Click Next.
- For the purposes of this demo, on the Incoming Connection page, select Allow access ONLY for users with these IP addresses. The IP address of the mail server is listed by default. Adding other machines' IP addresses into the access control list allows those machines to use this mail server. If you do not check this option, any machines that have a network connection to your computer can use the mail service, which could introduce unnecessary traffic to your computer.
- Click Next to continue the configuration:

- Select Immediately in the next window and click Next, so that the mail server will send messages out immediately.
- Select all the options in the next window and click Next:

- The next window shows you the server name and port number for the SMTP service. Take note of the outgoing SMTP mail server name,
as it will be used later in this article to configure the WebSphere Test Server.
In this case, the outgoing mail server name is
colinyu. Click Next:
- Click Finish to close the wizard and then click OK.
The next step is to test your new mail server. On the navigation bar, click the New Message icon. An e-mail composer will appear. Write a test message and click Save. This message will be saved in the Outbox of the mail server and will be automatically sent to the recipient:

Check your mailbox after a few minutes. If you receive the test message, your mail server is working properly. The next section will guide you through using a servlet to send JavaMail in Application Developer using the WebSphere Test Environment (WTE).
Writing a simple e-mail client
Start Application Developer V5.1:
- Go to the Windows Start menu.
- Select Programs => IBM WebSphere Studio => Application Developer 5.1.
Step 1. Starting a new EAR and Web project
Create a 1.3 EAR project with only the Web module:
- Select New => Projects => Enterprise Application Project.
- Select Create 1.3 J2EE Enterprise Application Project and then click Next.
- Enter
JavaMailSampleas the project name and then click Next. - Click on New Module to create a new Web project. Make sure only the Web Project is selected.
- Click Finish.
Step 2. Creating the server and server configuration
Create a WebSphere Test Environment V5 server and server configuration:
- Select File => New => Other.
- Select Server => Server and Server Configuration, and then click Next.
- Enter
WTE5as the server name and make sure WebSphere V5 Test Environment is selected. - Click Finish.
Step 3. Setting up a JavaMail session in the WebSphere Test Environment server
The embedded WTE server in Application Developer comes with a built-in mail provider. Start the WTE5 server and the administrative console:
- Switch to the Server Perspective. From the Workbench menu, select Window => Open Perspectives => Other => Server.
- In the Server Configuration view, expand Servers and double-click on WTE5 to open the Server Configuration editor.
- In the Server Configuration Editor, switch to the Configuration page.
- Select Enable administrative console, then save and close the editor.
- In the Server view, right-click on WTE5 and select Start.
- Wait until you see the message
Server is open for e-business. In the Server view, right-click on WTE5 and select Run administrative console.
Set up the mail session in the administrative console:
- Enter any user id and click OK.
- Expand Resources and select Mail Providers.
- Select Server and click Apply.
- Click Built-in Mail Provider.
- Click Mail Sessions.
- Click New to create a new mail session.
- Enter
mailsession1as the Name. - Enter
mail/mailsession1as the JNDI Name. - Enter the SMTP mail server name as the Mail Transport Host. For example, if you have a mail server from your ISP, enter that
mail server name here. If you configured your own PostCast mail server, enter the outgoing mail server name that you got earlier in this
text box (such as
colinyu). If the domain name is available, include it as well (such ascolinyu.ibm.com). Usinglocalhostas the server name for the PostCast server may not work as it requires additional configuration. - Make sure the Transport Protocol is smtp.
- Scroll down to the bottom of this page and click Apply.
- At the top of the page, click Save to save the configuration.
- Click Save again and close the Administrative Console window.
Figure 1. Creating a JavaMail session in the administrative console

Step 4. Creating a simple send mail servlet
This section guides you through the steps to create a servlet that sends e-mails. Create a servlet under the JavaMailSampleWeb folder:
- In the J2EE perspective -- J2EE Navigator, right-click on JavaMailSampleWeb and select New => Other.
- Select Web => Servlet and click Next.
- Enter
com.ibm.javamailsampleas the Package name. - Enter
TestServletas the Servlet name. Click Finish. - Add the boldface code below into the editor. Change the sender and receiver e-mails to your own.
For example, change
youremail@email.comto your own e-mail address. Save it.
package com.ibm.javamailsample;
import java.io.IOException;
import java.io.PrintWriter;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @version 1.0
* @author
*/
public class TestServlet extends HttpServlet {
/**
* @see javax.servlet.http.HttpServlet#void
(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
performTask(req, resp);
}
/**
* @see javax.servlet.http.HttpServlet#void
(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
performTask(req, resp);
}
public void performTask(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
try {
PrintWriter out = resp.getWriter();
out.println("hello");
javax.naming.InitialContext ctx =
new javax.naming.InitialContext();
javax.mail.Session mail_session =
(javax.mail.Session) ctx.lookup
("java:comp/env/mail/session1");
MimeMessage msg = new MimeMessage(mail_session);
msg.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse
("youremail@email.com"));
msg.setFrom(new InternetAddress
("jcyfung@ca.ibm.com"));
msg.setSubject("testing");
msg.setText("hello - testing");
Transport.send(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
} |
The above code uses the local JNDI name (java:comp/env/mail/session1) to look up the mail session.
As a result, you need to create a resource reference named mail/session1 in the Web Deployment Descriptor and bind the local
JNDI name (mail/session1) to the global JNDI name (mail/mailsession1) that you defined in Step 3.
Follow these steps to create a resource reference in the Web deployment descriptor:
- Switch to the J2EE perspective -- J2EE Navigator view.
- Under JavaMailSampleWeb, double-click on Web Deployment Descriptor to open the Web Deployment Descriptor editor.
- Select the References tab in the editor.
- Select the Resource tab at the top of the editor.
- Click Add to add a new resource reference and enter
mail/session1. - Click Browse to select the Type. Browse to
javax.mail.sessionand click OK. - In the WebSphere Bindings field, enter
mail/mailsession1as the JNDI name. This field refers to the global JNDI name of the mail session defined in the WebSphere Test Server during Step 4. - Save and close the Web Deployment Descriptor editor.
Figure 2. Setting up resource reference in the Web deployment descriptor

Restart the WTE5 server in order to pick up the new mail session settings from the admin console:
- Switch to the Server Perspective. Right-click on WTE5 and select Stop.
- Add the
JavaMailSampleEAR to the server. From the Server Configuration view, right-click on WTE5 and select Add => JavaMailSample. - Run the TestServlet. In the J2EE Perspective - J2EE Navigator, right-click on the TestServlet.java and select Run on Server.
- Select Use an existing server and make sure WTE5 is highlighted. Click Finish.
- Now check your e-mail and you should the test e-mail being sent to you by the servlet.
Extending the simple project into a real application
Many companies mail hardcopy catalogues to customers through postal mail, and let customers request a catalogue from the company Web site. The most straightforward implementation for this application is to store customer requests in a database, and then periodically, an employee checks the database and sends out catalogues.
JavaMail provides another way to implement this scenario. After a customer submits a catalogue request via the Web site, an e-mail containing the order request is sent to the company employee, who then sends out the catalogue. This implementation reduces the amount of code needed and can eliminate the need for a database. There are of course disadvantage to this approach. You still need a database if you want to persist customer information for future use. A combined approach might be preferable in that case. Nevertheless, the JavaMail approach provides a maintainable and convenient solution:
Figure 3. Catalogue request application using JavaMail API

The Web Project CatalogueRequest implements the JavaMail solution. CatalogueRequest.html
lets customers submit requests for hardcopy catalogues. After the submission, MailServlet sends an e-mail via the SMTP
server and the company's mail server to the employee's mailbox. You can download the implementation of this solution.
Follow these steps to set it up, assuming that the mail session is named mail/mailsession1 in the server configuration:
- Download the WAR file if you have not already done so.
- Select File => Import to import the downloaded WAR file into the workspace.
- Select WAR file and click Next.
- Browse to the downloaded WAR file.
- Make sure New Web project is checked.
- Enter
CatalogueRequestas the Web project name. - Select Existing EAR project.
- Browse to select JavaMailSample as the EAR project.
- Click Finish.
- In the J2EE perspective/J2EE Navigator view, expand CatalogueRequest/Java Source/com.ibm.javamailsample and then double-click on MailServlet to open it in the editor. Change the recipient e-mail address to your e-mail account.
- Change to the Server view. Right click on the WTE5 server => Restart.
- Expand CatalogueRequest/Web Contents. Right-click on CatalogueRequest.html and select Run on server.
- Fill in the information and submit the request form.
- Check your mailbox to see whether you received the e-mail with the request details.
Figure 4. CatalogueRequest.html

Figure 5. CatalogueResponse.html

| Name | Size | Download method |
|---|---|---|
| CatalogueRequest.zip | 13KB | FTP |
Information about download methods
Colin Yu is a software developer on the WebSphere Studio Application Developer team at the IBM Toronto Lab. Colin received a Bachelor of Engineering degree in 1995 and a Master of Applied Science degree from the University of Waterloo, Ontario in 2000. Colin is an IBM Certified Enterprise Developer and Systems Expert on WebSphere Application Server, and an IBM Certified Solution Developer on WebSphere Studio Application Developer and VisualAge for Java. You can reach Colin at coliny@ca.ibm.com .

Jane Fung works on the WebSphere Studio Application Developer Integration Edition tools team. Jane earned a Bachelor of Applied Science degree in Electrical Engineering at the University of Waterloo, Ontario, and is a Sun Java 2 Certified Programmer. You can reach Jane at jcyfung@ca.ibm.com .



