Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Using JavaMail in WebSphere Studio

Colin Yu (mailto:coliny@ca.ibm.com), Software Developer, IBM Toronto Lab
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 (mailto:jcyfung@ca.ibm.com), Software Developer, IBM Toronto Lab
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 .

Summary:  The JavaMail API provides a platform- and protocol-independent framework to build Java-based e-mail and messaging applications. This article focuses on building an application using the JavaMail API and unit testing the application in WebSphere Studio. It also provides information about a free e-mail server and a JavaMail scenario.

Date:  28 Oct 2003
Level:  Introductory

Activity:  4946 views
Comments:  

Introduction

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.


Prerequisites

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

  1. Download the installation image.
  2. Double-click the downloaded file, and the installation wizard should start.
  3. Click Next on the Welcome page.
  4. Accept the license agreement and click Next.
  5. Specify the installation location and click Next:
    Installation location
  6. Click Next again to start the installation.
  7. 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:

  1. From the Windows® Start menu, select Programs => PostCast Server => PostCast Server to start the Setup Wizard. Click Next.
  2. 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.
  3. Click Next to continue the configuration:
    Setup Wizard
  4. Select Immediately in the next window and click Next, so that the mail server will send messages out immediately.
  5. Select all the options in the next window and click Next:
    Setup Wizard
  6. 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:
    Setup Wizard
  7. 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:


Test message

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:

  1. Go to the Windows Start menu.
  2. 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:

  1. Select New => Projects => Enterprise Application Project.
  2. Select Create 1.3 J2EE Enterprise Application Project and then click Next.
  3. Enter JavaMailSample as the project name and then click Next.
  4. Click on New Module to create a new Web project. Make sure only the Web Project is selected.
  5. Click Finish.

Step 2. Creating the server and server configuration

Create a WebSphere Test Environment V5 server and server configuration:

  1. Select File => New => Other.
  2. Select Server => Server and Server Configuration, and then click Next.
  3. Enter WTE5 as the server name and make sure WebSphere V5 Test Environment is selected.
  4. 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:

  1. Switch to the Server Perspective. From the Workbench menu, select Window => Open Perspectives => Other => Server.
  2. In the Server Configuration view, expand Servers and double-click on WTE5 to open the Server Configuration editor.
  3. In the Server Configuration Editor, switch to the Configuration page.
  4. Select Enable administrative console, then save and close the editor.
  5. In the Server view, right-click on WTE5 and select Start.
  6. 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:

  1. Enter any user id and click OK.
  2. Expand Resources and select Mail Providers.
  3. Select Server and click Apply.
  4. Click Built-in Mail Provider.
  5. Click Mail Sessions.
  6. Click New to create a new mail session.
  7. Enter mailsession1 as the Name.
  8. Enter mail/mailsession1 as the JNDI Name.
  9. 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 as colinyu.ibm.com). Using localhost as the server name for the PostCast server may not work as it requires additional configuration.
  10. Make sure the Transport Protocol is smtp.
  11. Scroll down to the bottom of this page and click Apply.
  12. At the top of the page, click Save to save the configuration.
  13. Click Save again and close the Administrative Console window.

Figure 1. Creating a JavaMail session in the administrative console
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:

  1. In the J2EE perspective -- J2EE Navigator, right-click on JavaMailSampleWeb and select New => Other.
  2. Select Web => Servlet and click Next.
  3. Enter com.ibm.javamailsample as the Package name.
  4. Enter TestServlet as the Servlet name. Click Finish.
  5. Add the boldface code below into the editor. Change the sender and receiver e-mails to your own. For example, change youremail@email.com to 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:

  1. Switch to the J2EE perspective -- J2EE Navigator view.
  2. Under JavaMailSampleWeb, double-click on Web Deployment Descriptor to open the Web Deployment Descriptor editor.
  3. Select the References tab in the editor.
  4. Select the Resource tab at the top of the editor.
  5. Click Add to add a new resource reference and enter mail/session1.
  6. Click Browse to select the Type. Browse to javax.mail.session and click OK.
  7. In the WebSphere Bindings field, enter mail/mailsession1 as the JNDI name. This field refers to the global JNDI name of the mail session defined in the WebSphere Test Server during Step 4.
  8. Save and close the Web Deployment Descriptor editor.

Figure 2. Setting up resource reference in the Web deployment descriptor
Web deployment descriptor

Step 5. Testing the servlet

Restart the WTE5 server in order to pick up the new mail session settings from the admin console:

  1. Switch to the Server Perspective. Right-click on WTE5 and select Stop.
  2. Add the JavaMailSample EAR to the server. From the Server Configuration view, right-click on WTE5 and select Add => JavaMailSample.
  3. Run the TestServlet. In the J2EE Perspective - J2EE Navigator, right-click on the TestServlet.java and select Run on Server.
  4. Select Use an existing server and make sure WTE5 is highlighted. Click Finish.
  5. 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
Catalogue request application

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:

  1. Download the WAR file if you have not already done so.
  2. Select File => Import to import the downloaded WAR file into the workspace.
  3. Select WAR file and click Next.
  4. Browse to the downloaded WAR file.
  5. Make sure New Web project is checked.
  6. Enter CatalogueRequest as the Web project name.
  7. Select Existing EAR project.
  8. Browse to select JavaMailSample as the EAR project.
  9. Click Finish.
  10. 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.
  11. Change to the Server view. Right click on the WTE5 server => Restart.
  12. Expand CatalogueRequest/Web Contents. Right-click on CatalogueRequest.html and select Run on server.
  13. Fill in the information and submit the request form.
  14. Check your mailbox to see whether you received the e-mail with the request details.

Figure 4. CatalogueRequest.html
CatalogueRequest.html

Figure 5. CatalogueResponse.html
CatalogueResponse.html


Download

NameSizeDownload method
CatalogueRequest.zip 13KBFTP|HTTP

Information about download methods


About the authors

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

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 .

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere
ArticleID=13516
ArticleTitle=Using JavaMail in WebSphere Studio
publish-date=10282003
author1-email=mailto:coliny@ca.ibm.com
author1-email-cc=
author2-email=mailto:jcyfung@ca.ibm.com
author2-email-cc=