Java Reference
In-Depth Information
ex . printStackTrace ();
} finally { // Transport does not implement AutoCloseable :-(
if ( t != null ) {
try {
t . close ();
} catch ( MessagingException ex ) {
}
}
}
}
}
In this example I've taken advantage of multi-catch from Java 7. Unfortunately Trans
port does not implement AutoCloseable —the JavaMail API still needs to be compatible
with Java 6—so I do have to check whether the transport object is non-null, close it,
and catch and ignore any exceptions while closing, all in a finally block.
An alternative is to use the static Transport.send() method introduced in JavaMail
1.5, which does close itself internally. To do this, you configure the connection with
system properties.
Properties props = new Properties ();
props . put ( "mail.smtp.host" , "smtp.gmail.com" );
props . put ( "mail.transport.protocol" , "smtps" );
Session session = Session . getInstance ( props );
MimeMessage msg = new MimeMessage ( session );
try {
Address bill = new InternetAddress ( "god@microsoft.com" , "Bill Gates" );
Address elliotte = new InternetAddress ( "elharo@ibiblio.org" );
msg . setText ( "Resistance is futile. You will be assimilated!" );
msg . setFrom ( bill );
msg . setRecipient ( Message . RecipientType . TO , elliotte );
msg . setSubject ( "You must comply." );
Transport . send ( msg , "erharold" , "password" );
} catch ( MessagingException | UnsupportedEncodingException ex ) {
ex . printStackTrace ();
}
Sending Email from an Application
Example 2-1 is a simple application that sends a fixed message to a known address with
a specified subject. Once you see how to do this, it's straightforward to replace the strings
that give the message address, subject, and body with data read from the command line,
a GUI, a database, or some other source. For instance, Example 2-2 is a very simple GUI
for sending email. Figure 2-1 shows the program running.
Search WWH ::




Custom Search