Prev | Next | J2EETM Developer's Guide
Advanced Topics |
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:
Tips for running thepublic void sendNotice(String recipient) { try { Context initial = new InitialContext(); Session session = (Session) initial.lookup("java:comp/env/TheMailSession"); Message msg = new MimeMessage(session); msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, 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.setText(messageText); msg.setHeader("X-Mailer", mailer); msg.setSentDate(timeStamp); Transport.send(msg); } catch(Exception e) { throw new EJBException(e.getMessage()); } }
ConfirmerEJB
example:
recipient
variable to an actual email address.
Dialog Field
|
Value
|
---|---|
Coded Name | TheMailSession |
Type | javax.mail.Session |
Authentication | Application |
Field
|
Value
|
---|---|
JNDI Name | MyMailer |
From | (your email address) |
Host | (mail server host) |
User Name |
(your UNIX or Windows user name) |
Component/Reference Name
|
JNDI Name
|
---|---|
ConfirmerBean | MyConfirmer |
TheMailSession | MyMailer |
Note: If the application cannot connect to the mail server it will generate this exception:
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.javax.mail.MessagingException: Could not connect to SMTP host