Java Reference
In-Depth Information
L ISTING 8.1
Continued
// Instantiate a new MimeMessage and fill it with the
// required information.
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
// Hand the message to the default transport service
// for delivery.
Transport.send(msg);
}
catch (MessagingException mex) {
mex.printStackTrace();
}
8
}
}
In analyzing Listing 8.1, the first topic we must discuss is the Session class. The Session rep-
resents a mail session and is typically the first thing that you will set up in code using the
JavaMail API. It collects properties and defaults that will be used by different pieces through-
out the API.
In the following code snippet, you retrieve the system properties, add the JavaMail-specific
information to them, and retrieve a default session using them. The properties you use here are
just some of the JavaMail-specific attributes that can be used; however, they are the only ones
necessary to accomplish sending a simple message:
String host = “server.myhost.com”;
String to = “YourFriend@somewhere.com”;
String from = “MeMeMe@myhost.com”;
String subject = “JavaMail Rules!”;
String messageText = “I am sending a message using the”
+ “ JavaMail API.\nI can include any text that I want.”;
boolean sessionDebug = false;
// Create some properties and get the default Session.
Properties props = System.getProperties();
 
Search WWH ::




Custom Search