In this example, an e-mail message is sent to the user of a Web-based travel reservation system confirming the user’s reservation.
public String mailIt
(java.lang.String from,
java.lang.String to,
java.lang.String subject,
java.lang.String textmessage)
{
String status = “Your message was sent”;
try {
//Obtain the initial JNDI context
InitialContext ctx = new InitialContext();
//Perform a JNDI lookup to obtain the resource
//reference object
Session session = (Session) ctx.lookup
(“java:comp/env/mail/mymailserver”);
//Construct the message
MimeMessage message = new MimeMessage(session);
//Set the from address
Address[] fromAddress =
InternetAddress.parse(from);
message.addFrom(fromAddress);
//Set the to address
Address[] toAddress = InternetAddress.parse(to);
message.setRecipients(Message.RecipientType.TO,
toAddress);
//Set the subject and text
message.setSubject(subject);
message.setText(textmessage);
//Send the message
Transport.send(message);
} catch(AddressException e) {
status = “There was an error parsing the addresses”+e;
} catch(SendFailedException e) {
status = “There was an error sending the message”+e;
} catch (MessagingException e) {
status = “There was an unexpected error”+e;
} catch (NamingException e) {
status = “The mail session could not be created.”;
}
System.out.println(“The status is:”+ status);
return status;
}