Prev | Next

TOC | Index

J2EETM Developer's Guide
Advanced Topics

Sending Email from an Enterprise Bean

If you've ever ordered a product from a web site, you've probably received an email confirming your order. The ConfirmerEJB class demonstrates how to send email from an enterprise bean. (The sample code is in the doc/guides/ejb/examples/confirmer directory.)

In the sendNotice method of the ConfirmerEJB class, the lookup method returns a Session object, which represents a mail session. Like a database connection, a mail session is a resource. As with any resource, you must link the coded name (TheMailSession) with a JNDI name in the Resource References dialog box of the New Enterprise Bean Wizard. (See table 9-7). Using the Session object as an argument, the the sendNotice method creates an empty Message object. After calling several set methods on the Message object, sendNotice invokes the send method of the Transport class to send the message on its way. The source code for the sendNotice method follows:

public void sendNotice(String recipient) {

   try {
       Context initial = new InitialContext();
       Session session = 
         (Session) initial.lookup("java:comp/env/TheMailSession");
       Message msg = new MimeMessage(session);

          InternetAddress.parse(recipient, false));

       msg.setSubject("Test Message from ConfirmerEJB");
       DateFormat dateFormatter = DateFormat.getDateTimeInstance(
          DateFormat.LONG, DateFormat.SHORT);

       Date timeStamp = new Date();
       String messageText = "Thank you for your order." + `\n' +
          "We received your order on " + 
          dateFormatter.format(timeStamp) + ".";

       msg.setHeader("X-Mailer", mailer);


   } catch(Exception e) {
       throw new EJBException(e.getMessage());

Tips for running the ConfirmerEJB example:

TABLE 9-7 Resource Reference Dialog for the ConfirmerEJB Example

Dialog Field


Coded Name TheMailSession
Type javax.mail.Session
Authentication Application

TABLE 9-8 Resource Reference Tab for the ConfirmerEJB Example



JNDI Name MyMailer
From (your email address)
Host (mail server host)
User Name (your UNIX or Windows
user name)

TABLE 9-9 JNDI Names for the ConfirmerEJB Example



ConfirmerBean MyConfirmer
TheMailSession MyMailer

Note: If the application cannot connect to the mail server it will generate this exception:

javax.mail.MessagingException: Could not connect to SMTP host
To fix this problem, make sure that the mail server is running and that you've entered the correct name for the mail server host in the Resource Reference tab.

Prev | Next

TOC | Index

Copyright © 2000 Sun Microsystems, Inc. All rights reserved.