Section 15.2. Creating and Sending Messages


15.2. Creating and Sending Messages

JavaMail messages are encapsulated within the abstract Message class. Since JavaMail is a transport-independent API, the default message class is very generic. A standard Message has three attributes: a subject, a set of headers, and content. The Message class defines get- and set- methods for each of these. In addition, the Message class implements the Part interface, which defines a set of methods for dealing with message headers in an abstract fashion and for associating content with the message. The actual message content is contained in a javax.activation.DataHandler object, part of the JavaBeans Activation Framework.

Message origins and destinations are set via Address objects. Since Address is abstract, subclasses are provided to handle particular address types. The basic JavaMail implementation includes an InternetAddress class for SMTP mail and a NewsAddress class for NNTP (Usenet) news. Note that, because there is no NNTP service provider included with the JavaMail distribution, the InternetAddress class is of greater use to most programmers.

The easiest way to create an InternetAddress is to instantiate a new object, passing an RFC-822-formatted (user@host) address into the constructor:

     InternetAddress addr = new InternetAddress("adams@whitehouse.gov"); 

If the address format is invalid, an AddressException is thrown. You can also supply a personal name as a second parameter:

     InternetAddress addr = new InternetAddress(                                      "adams@whitehouse.gov", "John Adams"); 

Error-handling behavior for InternetAddress objects is a little odd. The basic constructor throws an exception if the address provided doesn't conform to the RFC 822 rules. However, if you supply a personal name, no AddressException is thrown, even if the address provided is improperly formatted.

JavaMail 1.3 introduced a strict flag to the InternetAddress constructor. However, there appears to be a bug in the reference implementation that causes this flag to be ignored. You can get around this by creating an empty InternetAddress object and setting the address property separately. If you subsequently want to validate the address, you can call the new validate( ) method. To summarize:

     // No exception:     InternetAddress address = new InternetAddress("test@", "John Test");     // Exception! (JavaMail 1.3.2, J2EE 1.4.1 RI)     InternetAddress address2 = new InternetAddress("test@", false);     InternetAddress ad1 = new InternetAddress( );     ad1.setAddress("bob@");  // doesn't throw exception     ad1.validate( );  // throws exception 

In most cases, this behavior does not make any differenceyou generally want strict parsing, since if JavaMail cannot understand the address, the mail server probably won't either. But some applications (such as email to fax gateways) do break the RFC 822 rules, so you should know how to handle cases like this.

Back to the matter at hand. The JavaMail distribution comes with one Message implementation: the MimeMessage class, which handles Internet email. Instantiating a simple MimeMessage is easy:

     Message msg = new MimeMessage(session);     msg.setFrom(new InternetAddress("tip@house.gov"));     msg.setRecipients(Message.RecipientType.TO,                       InternetAddress.parse("mike@state.ma.us", false));     msg.setText("We need to discuss a highway project."); 

Additional set methods can be called to set other attributes of the message, such as the subject, header fields, and so on. The Part interface also offers ways to set message content. The simplest is to use the setText( ) method, which sets the message content to a text string, with the content MIME type set to text/plain. The more fine-grained approach is to create a JAF DataHandler object, assign it content and MIME type, and use the setDataHandler( ) method to associate the DataHandler with the message. The equivalent of the setText( ) call would be:

     javax.activation.DataHandler dh = new javax.activation.DataHandler(                     "We need to discuss a highway project.", "text/plain");     msg.setDataHandler(dh); 

Other content types besides plain text are possible. To send HTML-formatted mail, pass the HTML into a DataHandler with the content type set to text/html.

15.2.1. Sending Messages

Once a message has been created, sending it is simple. The Address object identifies the type of address used (Internet email or Usenet news) so that the JavaMail API can determine the appropriate transport mechanism. The simplest way to do this is to call the static send(Message) method of transport. This approach uses the default session to determine mail servers (via the environment properties) and appropriate protocols (via javamail.address.map).

To obtain a little more control, you can retrieve a protocol-specific TRansport object from a Session:

     Transport t = session.getTransport("smtp");     t.send(msg); 

Example 15-1 puts all the pieces together, retrieving the default session, assembling a simple message, and using the default transport mechanism to send it.

Example 15-1. Sending an SMTP mail message
 import javax.mail.*; import javax.mail.internet.*; import java.util.Properties; public class MailSend {   public static void main(String[] args) {     Properties props = System.getProperties( );     props.put("mail.smtp.host", "mail.college.edu");     Session session = Session.getDefaultInstance(props, null);    try {      Message msg = new MimeMessage(session);      msg.setFrom(new InternetAddress("you@yourhost.com"));      msg.setRecipients(Message.RecipientType.TO,                        InternetAddress.parse("me@myhost.com", false));      msg.setSubject("Test Message");      msg.setText("This is the sample Message Text");      msg.setHeader("X-Mailer", "O'Reilly SimpleSender");      Transport.send(msg);    } catch (AddressException ae) {      ae.printStackTrace(System.out);    } catch (MessagingException me) {      me.printStackTrace(System.out);    }   } } 



Java Enterprise in a Nutshell
Java Enterprise in a Nutshell (In a Nutshell (OReilly))
ISBN: 0596101422
EAN: 2147483647
Year: 2004
Pages: 269

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