13.7. Sending Mail Messages

Sending Plain Text Messages

Plain text messages can be sent using a static convenience method:

Mail.send(to, from, subject, body);

You can use the standard format for email addresses, for example, [email protected], Person [email protected], and Person LastName [email protected]. Multiple recipients can be specified in a single string separated by commas.

To access the complete set of header attributes, create a Mail object, invoke the various set methods, and call send:

Mail msg = new Mail();
msg.setTo("User1 [email protected], User2 [email protected]");
msg.setFrom("Me [email protected]");
msg.setReplyTo("User3 [email protected]");
msg.setCc("User4 [email protected]");
msg.setBcc("User5 [email protected]");
msg.setSubject("this is the subject");
msg.setBody("this is the body");
msg.send();
Sending Rich Text Messages

Rich text messages (i.e. HTML) require using the setBody(html,alternate) method to specify both the HTML and plain text versions of a message to send out:

Mail msg = new Mail(to, from, subject);
msg.setBody("<p>This is the HTML body</p>",
            "This is the plain text body");
msg.send();
Attachments

Message attachments are handled using one of the various attach(...) methods. Support is provided for File, URL and ByteArray datasources. The URL datasource is the simplest to use (and can also fetch from a local file using the appropriate protocol specification). All attachments require a name, a description, and an optional disposition. The MIME type is determined automatically.

For example, the following code fragment shows how to attach an image whose content is fetched from a URL:

URL  url = new URL("http://example.com/image.gif");
Mail msg = new Mail(to, from, subject, body);
msg.attach(url, "image.gif", "A sample image");
           msg.send();

The protocol for attaching content from a local file is similar:

File path = new File("image.gif");
Mail msg  = new Mail(to, from, subject, body);
msg.attach(path, "image.gif", "A sample image");
msg.send();

The Mail service provides a utility class called ByteArrayDataSource that can be used to attach virtually any type of content contained in memory by supplying its data as a byte[] array.