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 () 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", ...

Get Java Enterprise in a Nutshell, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.