Combining SOAP and JavaMail
See how to use SOAP and other transport protocols
with JavaMail for asynchronous, XML messaging among applications

by Sameer Tyagi

Posted April 7, 2004

Like every other distributed computing architecture, Web services have also settled on a standard, well-known protocol for communication between distributed components of a system. For CORBA, the protocol was IIOP; for RMI, first it was JRMP and later it was IIOP; and in Microsoft environments it was DCOM.

For Web services architectures, the de facto standard for the basic protocol for communication between two parties is the Simple Object Access Protocol (SOAP). SOAP is transport protocol independent in that it specifies only the packaging structure of the XML message and sits on other protocols, HTTP in almost all cases. We will look at other transports: Simple Mail Transfer Protocol (SMTP) and Post Office Protocol (POP) and how SOAP can be used with JavaMail for asynchronous XML messaging among applications.

Business requirements sometimes dictate that the SOAP messages passed between business partners be handled asynchronously with some degree of reliability associated with the transfer. One would not want a critical purchase order to disappear midway because the underlying transport is not reliable or because the network was down. Java Message Service (JMS) is the preferred technology for integration and messaging between loosely coupled Java applications. While JMS is a specification that creates an abstraction at the application level rather than the wire protocol, JavaMail can be thought of as an object-oriented wrapper around the standard messaging protocols: SMTP, POP3, and IMAP. SMTP is used to send e-mail, while POP3 and IMAP are used to retrieve e-mail.

E-mail applications can be divided into two broad categories: Mail User Agent (MUA) and Mail Transfer Agent (MTA) applications. MUA applications like Eudora, Netscape Messenger, and Microsoft Outlook allow messages to be composed, accessed, and sent, while MTA applications like Sun One Messaging server and Microsoft Exchange handle the physical delivery. JavaMail is a standard extension API that is focused on building MUA functionality into Java applications. It is designed using a provider-based architecture (such as JMS) for wire protocol independence (see Figure 1).

The JavaMail API consists of three broad packages that contain both the client API and the API that serves as a contract for providers to implement. They also contain the classes and interfaces to model events, notifications, and searching. We will focus our discussion on sending and receiving messages.

Consider the concept behind sending mail messages using the JavaMail API (see Figure 2). A session is created to a server using an underlying provider. Message objects are created and sent using the Transport for that provider session. The semantics of how a provider establishes a session and the physical connection are abstracted from the application code.

The message is logically comprised of different sections (see Figure 3). It has some header attributes (to, from, subject, and so on) and the content data. E-mail messages that contain attachments are modeled as multipart messages. In a multipart message the body is comprised of many BodyPart objects.

Spreading the Word
To see how SOAP and JavaMail can be combined, let's look at an example of asynchronous messaging between two companies called BuyerCo and SellerCo. BuyerCo sends a purchase order, an XML or other binary document, to SellerCo using SOAP. To send a SOAP message, we'll follow the steps shown in Figure 3. The body of the mail message will be replaced with the SOAP envelope structure, and the XML file representing the purchase order will be sent as an attachment in the message. Listing 1 shows the code for sending this mail from to . The JavaMail API comes with providers from Sun for POP3, SMTP, and IMAP, hence, no vendor products—like Message Oriented Middleware (MOM) implementations—are needed to run this example.

The mail message can be retrieved at SellerCo.com, per the minimum steps required to retrieve mail using an underlying provider (see Figure 4). A Session object is used to obtain a store created for the POP3 protocol. The store is connected to a server using a username and password, and the users' folder is opened. Messages in the folder are then accessed and downloaded.

Listing 2 shows the code on SellerCo's side to access a POP3 server and download all messages using JavaMail, which simply dumps the message headers, content, and attachments to the console.

The rather simple JavaMail API can be used to build complex messaging applications. Consider the business use case of BuyerCo.com and SellerCo.com. BuyerCo places regular purchase orders for its main branch with SellerCo, which processes and ships the supplies. SellerCo then sends an invoice to BuyerCo that BuyerCo's accounting department processes and sends an electronic payment to SellerCo (see Figure 5):

  1. The client application initiates the business exchange by sending a SOAP message with the purchase order as an XML attachment using SMTP. The sender and recipient are indicated by the From and To e-mail headers. Buyer's local mail server acts as a sort of messaging provider and stores the message, which is reliably delivered (possibly with a delivery receipt) to SellerCo.com (see Listing 1).
  2. The PurchaseOrderService at SellerCo application either picks up the mail or is notified when the mail arrives. It downloads the mail and processes the headers and the body that contains a SOAP message. It also extracts the attachment, which contains the order and processes it (see Listing 2).
  3. The SendInvoice application is invoked, which now acts like a client and sends the invoice to BuyerCo, as in step 1.
  4. BuyerCo's AccountingService picks up the message containing the invoice, as in step 2, and processes the payment to SellerCo.

This process shows how an asynchronous message exchange scenario can be built using JavaMail and XML technologies. Java need not be used on both sides. For example, SellerCo could use VB or C++ to download e-mail from their servers.

E-Mail Advantages
Messaging with JavaMail, and in particular SOAP messaging with JavaMail, offers several advantages.

No need for expensive MOM: The sender and receiver do not need any JMS infrastructure or vendor software, which is especially significant for non-Java environments.

Security support: Most developers of e-mail applications have two broad concerns: authentication and encryption. Basic authentication is built into e-mail, and most of the enterprise e-mail servers provide secure mail using techniques like PGP and S/MIME. Thus, the work required in building security into the application layer is reduced. Another layer of security can be added with the use of digital certificates, much like it is used in e-mail to identify senders.

Existing infrastructure can be leveraged: E-mail is the first enterprise solution that any company implements. Most organizations have sophisticated hardware and software infrastructures in place to support this corporate lifeline that guarantees a high quality of service. Messaging with JavaMail and XML can leverage this existing infrastructure to build interoperable asynchronous messaging solutions.

Message-sorting facilities can be provided: Messages in the server can be searched, sorted, and filtered from applications using headers (subject, to, from, and so on) and even message content if needed.

Notification support: Instead of using a latent polling approach, mailbox-monitoring services allow message servers to be monitored in case new messages arrive. While an e-mail is an asynchronous, one-way message exchange, SMTP offers a delivery notification mechanism called Delivery Status Notification (DSN) and Message Disposition Notification (MDN) in which a receipt e-mail message is sent back.

Delivery to multiple recipients supported: The same message can be delivered to multiple recipients. Audit trail services can also be built using the "bcc" feature.

Low implementation cost: Messaging solutions using JavaMail are generally less expensive because most of the infrastructure already exists and no MOM products are required.

Some Disadvantages
JavaMail has some limitations for enterprise messaging and integration.

No transaction support: Although mail-based messaging solutions use a tried and tested technology, there is no transaction support across enterprise boundaries. Most architects interpret that as an absolute design constraint for any adoption. If there is no stringent requirement on transactions across enterprise boundaries, then architectures as those outlined in Figure 5 can be a good fit.

Repeated delivery of the same message: Just as receiving the same e-mail in one's mailbox twice is a common occurrence, the same message may be delivered to applications multiple times. There is no concept of "once and only once" guaranteed delivery support in a mail-based solution. The application layer needs to incorporate the logic of filtering this out if such an event would affect the business process. For example, the receiving end would need to check if the same purchase order was processed earlier.

No well-defined standards for service description: One could argue that WSDL 1.1 specifies bindings for HTTP only, so there is no standard way of describing SMTP bindings. It is true that there are no clear specifications on the use of SMTP with SOAP, but this argument can be made for any protocol besides HTTP. However, WSDL 1.1 describes some examples of how an SMTP end point can be used with a "mailto" URI.

We have looked at how existing messaging infrastructure can be leveraged to build a SOAP-based, application-to-application messaging solution. This kind of architecture is not necessarily the one-stop solution to all asynchronous messaging needs. If the application has stringent business requirements such as nonrepudiation of receipt or once-and-only-once delivery, then a more robust, Web services-based, asynchronous messaging solution like ebXML Message Service (ebMS) or WS-Reliability may be needed.

Another alternative is to use SMTP/POP bindings under an API like JAX-RPC, and the Jaxmail Project on Java.net seeks to provide this functionality (see Resources). Still, the lightweight architecture outlined here can be useful for applications that require asynchronous, reliable messaging when developers can't incur the cost of using complex and evolving SOAP messaging protocols and their associated vendor products. Existing e-mail infrastructure, which is present in every enterprise, can be used, and since e-mail is the backbone of any enterprise, most of the failover and recovery mechanisms also already exist. Try it and see how it works for you.

About the Author
Sameer Tyagi works as a Java architect with Sun Microsystems. His publications include industry periodicals and books on Java/J2EE technologies, including Java Web Services Architecture (Morgan Kauffman, 2003) to which portions of this article are credited. Contact Sameer at .