Sending Email


Properties props = new Properties( ); props.put("mail.smtp.host", "mail.yourhost.com"); Session session =    Session.getDefaultInstance(props, null); Message msg = new MimeMessage(session); msg.setFrom(new    InternetAddress("tim@timothyfisher.com")); InternetAddress toAddress =    new InternetAddress("kerry@timothyfisher.com"); msg.addRecipient(Message.RecipientType.TO,                   toAddress); msg.setSubject("Test Message"); msg.setText("This is the body of my message."); Transport.send(msg);



In this phrase, we send a plaintext email message using an SMTP server. There are six basic steps that you should always follow when you want to send email using the JavaMail API. These steps are identified here:

1.

Create a java.util.Properties object, which you will use to pass information about the mail server.

2.

Put the hostname of the SMTP mail server into the Properties object. Also, put any other properties you want to set into the Properties object.

3.

Create Session and Message objects.

4.

Set recipients' and sender's email addresses and the message subject in the Message object.

5.

Set the message text in the Message object.

6.

Call the TRansport.send() method to send the message.

We follow each of these steps in this phrase to create and send an email message. Note that the From and To addresses are created as InternetAddress objects. An InternetAddress object represents a valid email address. An exception will be thrown if you attempt to create an InternetAddress object using an invalid email address format. When you specify the To recipients, you also specify the type of the recipient. Valid types are TO, CC, and BCC. These are represented by the following constants:

Message.RecipientType.TO Message.RecipientType.CC Message.RecipientType.BCC


The Message class is an abstract class defined in the javax.mail package. There is one subclass that implements the Message class that is part of the standard JavaMail reference implementation. This is the MimeMessage class, which is the implementation we use in our phrase here. This implementation represents a MIME style email message. You should be able to use this for most, if not all, of your email needs.

In this phrase, we use the Properties object to pass only the SMTP mail host. This is the only required property that you must set. There are additional properties that you can set, though.

Note

See the javax.mail package overview in the JavaDoc for additional detail on other email related properties that you can pass in the Properties object: http://java.sun.com/javaee/5/docs/api/javax/mail/package-summary.html





JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net