Sending an e-mail using EmailConnection

The EmailConnection class provides a simple way to send an e-mail, including an e-mail that contain attachments, in IBM® WebSphere® sMash applications.

Overview

An application can use the methods of EmailConnection to describe the properties of an e-mail and send it to an SMTP server. The EmailConnection class is an extension of the Connection API with specialized methods to construct a Connection API request for the SMTP protocol.

The relationship between the base Connection API and the EmailConnection extension can be seen in the following examples. This first example uses the base Connection API:

try {
    Connection conn = new Connection("mailto:you@projectzero.org", Connection.Operation.POST);
    conn.addRequestHeader("From", "me@projectzero.org");
    conn.addRequestHeader("Subject", "Hello!");
    conn.addRequestHeader("Content-Type", "text/plain; charset=\"UTF-8\"");
    conn.addRequestHeader("X-My-Custom-Header", "Custom header value");
    conn.setRequestBody("This is the e-mail body.");
    Connection.Response resp = conn.send();
} catch (Exception e) {
    // failed to send e-mail
}

In the above example, the application uses the Connection API with the POST operation and a resource name that is a mailto: URL. The properties of the e-mail are set as request headers and the e-mail is sent using the send() method.

The next example uses the EmailConnection extension to send a similar e-mail message:

try {
    EmailConnection email = new EmailConnection("you@projectzero.org");
    email.setFromAddress("me@projectzero.org");
    email.setSubject("Hello!");
    email.addRequestHeader("X-My-Custom-Header", "Custom header value");
    email.setContent("This is the e-mail body.", "text/plain; charset=\"UTF-8\"");
    email.send();
} catch (Exception e) {
    // failed to send e-mail
}

In the above example, the application uses the specialized methods of the EmailConnection extension to set up the properties of the e-mail but still uses addRequestHeader() of the base Connection API to set up a custom header. The message is sent using the send() method.

See the API reference for zero.core for more information about Connection, EmailConnection and associated interfaces.

Configuration

The smtp protocol implementation used by the EmailConnection class requires some configuration in zero.config. The minimum configuration is the host name of the SMTP server to be used, which is most easily defined using a clause similar to the following example:

/config/connection/defaults/smtp/hostname = "smtp.projectzero.org"

Additional configuration can be used to specify other properties for the smtp protocol implementation, such as port number, AUTH PLAIN authentication credentials and SSL configuration (SMTPS). For more information, see the SMTP protocol documentation.

Sending a simple text e-mail

The following code extract illustrates how to send a simple text e-mail using zero.core.connection.EmailConnection:

try {
    EmailConnection email = new EmailConnection("you@projectzero.org");
    email.setFromAddress("me@projectzero.org");
    email.setSubject("Hello!");
    email.setContent("This is the email body.");
    email.send();
} catch (Exception e) {
    // failed to send email
}

In this example, the application creates a new EmailConnection and specifies the recipient's e-mail address. The mailto: prefix is added if it is not already present and the Connection request is automatically set to use the POST operation.

  • EmailConnection(String address)

The methods of the EmailConnection object are used to set up the e-mail request headers:

  • void setFromAddress(String address)
  • void setSubject(String subject)

The content of a simple text e-mail can be specified using either a String or Reader object. If the application does not specify a content type, the default value of text/plain; charset=\"UTF-8\" is used.

  • void setContent(String content)
  • void setContent(String content, String contentType)
  • void setContent(Reader content)
  • void setContent(Reader content, String contentType)

After the e-mail is prepared, the send() method is used to submit the request using the connection infrastructure. The send() method calls the Connection.setRequestBody() and send() methods, and throws an IOException or ConnectionException if the send processing fails.

  • Connection.Response send()

Sending an e-mail with attachments

The EmailConnection class provides two methods to allow additional content to be sent in the e-mail message:

  • void addAttachment(Object attachment, String contentType, String filename)
  • void addInlineContent(Object inlineContent, String contentType, String contentLocation)

Calling either of these methods causes the send() method to submit a MultipartBody object as the request body. The the primary content is specified by setContent().

The following example uses addAttachment() to include a separate text document as an e-mail attachment:

try {
    EmailConnection email = new EmailConnection("you@projectzero.org");
    email.setFromAddress("me@projectzero.org");
    email.setSubject("Hello to you");
    email.setContent("Please read the attachment.");
    email.addAttachment("This is the content of the attachment",
                        "text/plain; charset=\"UTF-8\"",
                        "attachment.txt");
    email.send();
} catch (Exception e) {
    // failed to send e-mail
}

In this example, the content of text document is specified as a String, but it is also possible to use Reader for character data, or byte[] or InputStream for binary data. The application must specify the content type of the attachment and should include a charset parameter for character data to ensure that the data is encoded correctly. The final argument specifies the file name, in this case attachment.txt, that is presented when the recipient reads the e-mail.

Here is a more complex example that demonstrates sending an e-mail containing a HTML message and an inline image:

try {
    EmailConnection email = new EmailConnection("you@projectzero.org");
    email.setFromAddress("me@projectzero.org");
    email.setSubject("Hello to you");
    email.setContent("<html><p>This email has an inline image! <img src=\"images/zero.png\"></p></html>",
                     "text/html; charset=\"UTF-8\"");
    InputStream imageData =
        Connection.doGET("file:///~/images/ZeroGraphic.png").getResponseBodyInputStream();
    email.addInlineContent(imageData, "image/png", "images/zero.png");
    email.send();
} catch (Exception e) {
    // failed to send e-mail
}

The main things to note in this example are as follows:

  • The setContent() method is used to specify an HTML body as a String and to specify an appropriate content type and character encoding.
  • The image data is supplied as an InputStream, which in this case is read from a file using another invocation of the Connection API.
  • The inline image is added to the e-mail using addInlineContent(), specifying the input stream, content type, and a content location. This content location matches the src attribute of the img tag in the HTML document.

Sending an e-mail to multiple recipients

The EmailConnection constructor allows a single e-mail address to be specified. This e-mail address forms the resource name of the Connection request and hence becomes the primary recipient of the e-mail. An e-mail can be sent to additional recipients using the following methods:

  • void addRecipient(String address)
  • void addCcRecipient(String address)
  • void addBccRecipient(String address)

The addRecipient(), addCcRecipient(), and addBccRecipient() methods add a single address to the To, Cc and Bcc request headers, respectively. All named recipients are sent a copy of the e-mail but Bcc header values are not included in the headers of the transmitted message.

Version 1.1.30763