Oracle Internet File System Developer's Guide Release 1.1 A75172-04 |
Library | Service | Contents | Index

# 10
Sending E-mail Programmatically

This chapter covers the following topics:

- What Is Sending E-mail Programmatically?

- Writing an Application to Send E-mail Programmatically

- Sample Code: Sending E-Mail Programmatically

## What Is Sending E-mail Programmatically?

We are all familiar with using standard e-mail clients to create and send e-mail messages. However, e-mail can also be created and sent by an application program. This type of e-mail is called programmatic e-mail.

When a user inserts, updates, or deletes a file, your custom application can perform the following tasks:

- Generate an e-mail message notifying one or more other users of the change.

- Send the message using the Oracle Internet File System programmatic e-mail capability.

The message is staged in the Oracle iFS Outbox to await delivery.

Programmatic e-mail takes place in a transactional environment. Applications that require transactional capability include multiple activities, one of which is an e-mail notification. For the application to complete the task, the application must perform some action and then send a notification of that action. The action and the notification must be so tightly linked that you want both to be rolled back if the message is not accepted by the Outbox. Here are the stages of the process:

- Perform the action.

- Create the message using the Oracle iFS e-mail API.

- Insert the message in the Outbox.

An example of this type of application would be creating a new customer account, then sending a message to the customer saying, "Here is your new account number and password." If the message cannot be sent, the account and password are rolled back. The Oracle iFS framework for programmatic e-mail provides a mechanism for Oracle iFS applications to send such e-mail messages.

### Oracle iFS Infrastructure for Programmatic E-mail

The Oracle iFS infrastructure for programmatic e-mail includes the Outbox folder and the IfsMessage class.

The Outbox folder is the location where messages are staged to await delivery. A system-wide Oracle iFS Outbox is created during the installation process. An Outbox agent delivers mail present in the Outbox on an event-driven basis.

The Oracle iFS API class, IfsMessage, provides methods to create and send e-mail programmatically. All e-mail consists of three parts:

- Header information, such as To, From, and Subject

- Body (optional)

- Attachments (optional)

The methods of the IfsMessage class allow you to set appropriate values for each of these parts.

### Programmatic E-mail Scenario

One common use of programmatic e-mail is to use an application program to respond automatically to customer actions. For example, in an e-commerce application:

- A customer logs onto your company's e-commerce web site.

- The customer submits an order.

- The company wants to send an automatic e-mail confirmation of the order.

To create this automatic e-mail confirmation, you use information from multiple sources. Some information comes from the customer, such as name and e-mail address. Other information comes from your company, such as text for the confirmation message and any attachments, such as an invoice.

The application program must perform three tasks:

- Gather the information from appropriate sources.

- Using the information, create a message object.

- Send the e-mail message to the customer.

## Writing an Application to Send E-mail Programmatically

To write a programmatic e-mail application, follow these steps:

1. Create an IfsMessage Object

2. Construct the Message Header

3. Construct the Message Body

4. Send the Message

For more information about e-mail methods, see the Javadoc for the `oracle.ifs.adk.mail.IfsMessage` class.

### Option for Sending Short Messages

Note that if you want to send a very short mesage, you can use the convenience method, oracle.ifs.adk.mail.IfsMessage.sendMessage(). To use sendMessage(), supply the following parameters, as appropriate:

Parameter | Datatype
--- | ---
Session | LibrarySession
To | String[]
CC (Carbon Copy) | String[]
BCC (Blind Carbon Copy) | String[]
Subject | String
Body | Reader

#### Sample Code: Send a Short Message

    // Use the convenience method to send a short message.
         mail.sendMessage(currentSession,"Recipient", "CcRecipient", "BccRecipient",

               "Subject:Sending Short Messages","This is a one-sentence message.");

### Create an IfsMessage Object

Creating a database connection is the first task of every Oracle iFS application, and requires both LibraryService and LibrarySession. For a complete sample of the standard technique for obtaining the current Library Session, see "Sample Code: Sending E-Mail Programmatically".

In this case, LibrarySession is the single parameter passed to the IfsMessage constructor.

For more information about LibraryService and LibrarySession, see Chapter 2, "API Overview":

- "The LibraryService Class"

- "The LibrarySession Class"

#### Sample Code: Create an IfsMessage Object

Before you create the message object, check to be sure the current user has Admin privileges.

Note: Only users with Admin Mode enabled can send e-mail programmatically.

    // Check that user is in Admin Mode.
    if (user.isAdminEnabled())
            session.setAdministrationMode(true);

    // Use the IfsMessage constructor to create a message object.
         IfsMessage msg = new IfsMessage(session);

### Construct the Message Header

To construct the message header, supply one or more of the following pieces of information:

Item | Datatype | Required/Optional | Setter
--- | --- | --- | ---
To | String | See Note. | `setToHeader()`
CC (Carbon Copy) | String | See Note. | `setCcHeader()`
BCC (Blind Carbon Copy) | String | See Note. | `setBccHeader()`
From | String or DirectoryUser | Automatically inserted; optional. | `setFromHeader()`
Sender | String or DirectoryUser | Automatically inserted; optional. | `setSenderHeader()`
ReplyTo | String | Optional. | `setReplyToHeader()`
In Reply To | Message | Optional. | `setInReplyToHeader()`
Subject | String | Optional. | `setSubject()`

#### Using Multiple Values for Header Items

Multiple values are allowed for each of the following header items:

- To

- CC

- BCC

- From

- Reply To

For example, to send the same message to multiple destinations, you could set three To headers and six CC headers. Any combination of the header items is acceptable, as long as at least one recipient is indicated. In other words, each message must have either a To, CC, or BCC specified, so the message can be delivered.

In some cases, one person will send mail on behalf of another person. In that case, you can specify a From value (the author of the message) that varies from the Sender value (the person who sends the message). If setFromHeader() is omitted, the From value will be set to the current user by default. If setSenderHeader() is provided, but not setFromHeader(), the value provided for Sender will be used for From and Sender will be omitted.

For details of the setter methods for the message header, see the Javadoc for `oracle.ifs.adk.mail.IfsMessage.` All of the setter methods are overloaded to provide one method that accepts a single String value and another that accepts a String array.

#### Sample Code: Construct the Message Header

     msg.setFromHeader("tuser99@us.oracle.com");
     msg.setSenderHeader(user);  //Refers to a DirectoryUser
     msg.setToHeader("guest@us.oracle.com");
     msg.setBccHeader("tuser51@us.oracle.com");
     msg.setSubject("iFS email API: Mail with multi-part body");

### Construct the Message Body

To construct the message body, you can use any of the variants of the setBody() method, and, optionally, of the attach() methods.

Methods | Datatype | Required/Optional | Item
--- | --- | --- | ---
`setBody(String body)` | String | Optional. | Body
`setAlternativeBodies (IfsMessage.MimeBodyPart[])` | MimeBodyPart[] | Optional. | Alternative bodies
`setMixedBodies (IfsMessage.MimeBodyPart[])` | MimeBodyPart[] | Optional. | Mixed bodies
`setParallelBodies (IfsMessage.MimeBodyPart[])` | MimeBodyPart[] | Optional. | Parallel bodies
`attach(String path)` | String | Optional. Use to indicate path to document file. | Attachment
`attach(String[] path)` | String[] | Optional. Use to indicate an array of paths to document files. | Attachment
`attach(Document doc)` | Document | Optional. Attach one document. | Attachment
`attach(Document[] doc)` | Document[] | Optional. Attach an array of documents. | Attachment

#### Using the setBody() methods

The setBody() method is overloaded to accept several combinations of arguments, and includes 11 variants. For more information on methods used to construct the message body, see the Javadoc for `oracle.ifs.adk.mail.IfsMessage.`

Here are some basic guidelines:

- Use setBody() for a message with no attachments.

- If the message has an attachment, you must use one of the three setXxxBodies() methods:

  - setMixedBodies()

  - setAlternativeBodies()

  - setParallelBodies()

#### The setMixedBodies() Method

The setMixedBodies() method will meet most application needs for sending any message with an attachment. The multipart/mixed content type is the most general MIME content type, and can be used for any multipart message or any message with attachments. The client is free to choose the method to display the message. Generally, the different body parts are treated as different parts of the message; that is, they are treated the same as if they were attachments.

When you pass only a single parameter to setMixedBodies(), rather than an array, setMixedBodies has the same effect as the setBody() method.

#### The setAlternativeBodies() Method

Use setAlternativeBodies() to specify alternative formats for use by specific browsers. A multipart/alternative body is a body of multiple body parts of the same content but in different formats. A compatible client should choose the most appropriate format to display the message to the user.

The content type of the message is always multipart/alterative if the message does not have attachments. Otherwise, the message content type will be multipart/mixed with a nested multipart/alternative message.

When you pass only a single parameter to setAlternativeBodies(), rather than an array, setAlternativeBodies() has the same effect as the setBody() method.

#### The setParallelBodies() Method

Use setParallelBodies() when all attachments are of a format that can be displayed following the message, rather than included as a separate file. A multipart/parallel body is a message body with multiple body parts that should be viewed in parallel using a compatible client.

The content type of the message is always multipart/parallel if the message does not have attachments. Otherwise, the message content type will be multipart/mixed with a nested multipart/parallel message.

When you pass only a single parameter to setParallelBodies(), rather than an array, setParallelBodies() has the same effect as the setBody() method.

#### Sample Code: Construct a Simple Message Body

    msg.setBody("Hello there! This is a simple string body.");

#### Sample Code: Construct a Multipart Message Body

    //Construct a multipart message body using setAlternativeBodies().
    MimeBodyPart[] bodies = new MimeBodyPart[2];
    bodies[0] = new MimeBodyPart("Hello, this is plain text.",
                                    "text/plain", null);
    bodies[1] = new MimeBodyPart("<html><body>Hello, this is HTML text " +
                                    ".</body></html>", "text/html", null);
    msg.setAlternativeBodies(bodies);

In this example, note the class MimeBodyPart. MimeBodyPart is a class that represents a single body part of a multipart MIME message. This class provides a means to group the essential information of a message body part into a single class for ease of storage and retrieval. MimeBodyPart is an inner class of the IfsMessage class; many methods of IfsMessage accept MimeBodyPart objects as arguments.

#### Sample Code: Add an Attachment

     // Add a document object attachment.
     msg.attach(doc);

### Send the Message

To send the message, use the oracle.ifs.adk.mail.IfsMessage.send() method, with no arguments. The only validation the send() method performs is to be sure that one of the recipient fields is set (To, CC, or BCC). All other validation is performed by the outgoing e-mail protocol. The Outbox agent will automatically pick up messages from the outbox. The Outbox agent passes all messages to the SMTP port on the local machine.

#### Sample Code: Send the Message

    msg.send();

Note that this method will return the following error messages if the message cannot be sent:

- 11031: Either From or Sender header must be present.

- 11032: Either To, Cc or Bcc header must be present.

## Sample Code: Sending E-Mail Programmatically

    package oracle.ifs.adk.mail;
    /* --IfsMailTest.java-- */

    import oracle.ifs.beans.DirectoryUser;
    import oracle.ifs.beans.Document;
    import oracle.ifs.beans.FolderPathResolver;
    import oracle.ifs.beans.LibrarySession;
    import oracle.ifs.common.IfsException;
    import oracle.ifs.beans.LibraryService;
    import oracle.ifs.protocols.email.beans.Mailbox;
    import oracle.ifs.adk.mail.IfsMessage.MimeBodyPart;

    public class IfsMailTest
    {
      public static void main(String[] args)
      {
        try
        {
          // Setting up the service, session, and user
          LibraryService service = new LibraryService();
          ClearTextCredential me = new ClearTextCredential("tuser1", "tuser1");
          ConnectOptions options = new ConnectOptions();
          options.setLocale(Locale.getDefault());
          LibrarySession session = service.connect(me, options);
          DirectoryUser user = (DirectoryUser) session.getDirectoryUser();
          if (user.isAdminEnabled())
            session.setAdministrationMode(true);

          IfsMessage msg = new IfsMessage(session);

          // Example 1
          // Creating a simple message being sent to two destinations.
          // The message has a simple string body.
          //
          IfsMessage msg = new IfsMessage(session);
          msg.setToHeader(new String[] {"guest@us.oracle.com",
                                        "tuser51@us.oracle.com"});
          msg.setFromHeader("tuser99@us.oracle.com");
          msg.setSenderHeader(user);
          msg.setCcHeader("tuser51@us.oracle.com");
          msg.setBccHeader("tuser51@us.oracle.com");
          msg.setContentType("text/plain");
          msg.setSubject("iFS email API: Mail with body and multiple recipients");
          msg.setBody("Hello there! This is a simple string body");
          msg.send();

          //Example 2
          // Creating a simple message being sent to two destinations.
          // The message has a multipart alternative structure.
          //
          IfsMessage msg = new IfsMessage(session);
          msg.setFromHeader("tuser99@us.oracle.com");
          msg.setSenderHeader(user);
          msg.setToHeader("guest@us.oracle.com");
          msg.setBccHeader("tuser51@us.oracle.com");
          msg.setSubject("iFS email API: Mail with multi-part body");
          MimeBodyPart[] bodies = new MimeBodyPart[2];
          bodies[0] = new MimeBodyPart("hello this is plain text.",
                                       "text/plain", null);
          bodies[1] = new MimeBodyPart("<html><body>hello this is a html text " +
                                       ".</body></html>", "text/html", null);
          msg.setAlternativeBodies(bodies);
          msg.send();

          //Example 3
          // Creating a simple message being sent to two destinations.
          // The message has a multipart mixed structure.
          //
         IfsMessage msg = new IfsMessage(session);
          msg.setFromHeader("tuser99@us.oracle.com");
          msg.setSenderHeader(user);
          msg.setToHeader("guest@us.oracle.com");
          msg.setCcHeader("tuser51@us.oracle.com");
          bodies = new MimeBodyPart[3];
          bodies[0] = new MimeBodyPart("This is plain text again.",
                                       "text/plain", null);
          bodies[1] = new MimeBodyPart("<html><body>This is html text. " +
                                       "</body></html>", "text/html",
                                       IfsMessage.ASCII_CHARSET);
          bodies[2] = new MimeBodyPart("<html><body>hello this is another html " +
                                       "text.</body></html>", "text/html",
                                       IfsMessage.ISO88591_CHARSET);
          msg.setMixedBodies(bodies);

          //
          // Associate attachments for Example 3.
          //
          FolderPathResolver resolver = new FolderPathResolver(session);
          Document doc = (Document) resolver.findPublicObjectByPath(
                                               "/home/tuser1/test.txt");
          msg.attach(doc);
          doc = (Document) resolver.findPublicObjectByPath("/home/tuser1/test.jpg");
          msg.attach(doc);

          msg.send();
        }
        catch (IfsException e)
        {
          e.printStackTrace();
        }
      }
    }

| Copyright © 2000 Oracle Corporation. All Rights Reserved. |
Library | Service | Contents | Index