Java Reference
In-Depth Information
@Asynchronous
public Future<String> sendMessage(String email) {
String status;
try {
Message message = new MimeMessage(session);
message.setFrom();
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(email, false));
message.setSubject("Test message from async example");
message.setHeader("X-Mailer", "JavaMail");
DateFormat dateFormatter = DateFormat
.getDateTimeInstance(DateFormat.LONG,
DateFormat.SHORT);
Date timeStamp = new Date();
String messageBody = "This is a test message from the async
example "
+ "of the Java EE Tutorial. It was sent on "
+ dateFormatter.format(timeStamp)
+ ".";
message.setText(messageBody);
message.setSentDate(timeStamp);
Transport.send(message);
status = "Sent";
logger.log(Level.INFO, "Mail sent to {0}", email);
} catch (MessagingException ex) {
logger.severe("Error in sending message.");
status = "Encountered an error";
logger.severe(ex.getMessage() +
ex.getNextException().getMessage());
logger.severe(ex.getCause().getMessage());
}
return new AsyncResult<String>(status);
}
The web client consists of a Facelets template,
template.xhtml
, two Facelets clients,
index.xhtml
and
response.xhtml
, and a JavaServer Faces managed bean,
MailerManagedBean
. The
index.xhtml
file contains a form for the target email
address. When the user submits the form, the
MailerManagedBean.send
method is
called. This method uses an injected instance of the
MailerBean
session bean to call
MailerBean.sendMessage
. The result is sent to the
response.xhtml
Facelets
view.