+ All Categories
Home > Documents > Javamail for Providers-150193

Javamail for Providers-150193

Date post: 09-Apr-2018
Category:
Upload: leonard-tiberiu-sandor
View: 229 times
Download: 0 times
Share this document with a friend
38
1 JavaMail TM Guide f or Service Providers Sun Microsystems, Inc. 901 San Antonio Road Palo Alto, CA 94303 USA 650 960-1300 fax 650 969 -91 31 Revision 01, August 1998
Transcript
Page 1: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 1/37

1

JavaMailTM

Guide forService Providers

Sun Microsystems, Inc.

901 San Antonio RoadPalo Alto, CA 94303 USA

650 960-1300 fax 650 969-9131

Revision 01, August 1998

Page 2: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 2/37

 August 1998

 JavaMail Guide for Service Providers

Copyright 1998 Sun Microsystems, Inc., 901San Antonio Road, PaloAlto, California 94303 U.S.A. All rights reserved.

This prod uct or documen tation is protected by copyrigh t anddistributed u nd er licenses restricting its use, copying, distribution,and d ecompilation.N o part of this product or documentation maybe reprodu ced in any form by any means without pr ior writtenauth orization of Sun and its licensors, if any.Third -party software,

includ ing font technology, is copyrigh ted and licensed from Sunsuppliers.

Sun, Sun Microsystems, the Sun logo, Java, JavaSoft, JavaMail,JavaBeans, JDK, and Solaris are trademar ks or registered trad emarksof Sun Microsystems, Inc.in the U.S. and other countries.

The OPEN LOOK and Sun™ Graph ical User Interface wasdeveloped by Sun Microsystems, Inc.for its users and licensees.Sunacknowledg es the pioneering efforts of Xerox in researching an ddeveloping the concept of visual or graphical user interfaces for the

compu ter indu stry. Sun hold s a non -exclusive license from Xerox tothe Xerox Grap hical User Inter face, which license also covers Sun’slicensees wh o implement OPEN LOOK GUIs and otherw ise complywith Sun’s written license agreements.

U.S. Government app roval required w hen exporting the prod uct.Use, duplication, or disclosure by the U.S. Govt is subject torestrictions of FAR 52.227-14(g)(2)(6/ 87) and FAR 52.227-19(6/ 87),or DFAR 252.227-7015 (b)(6/ 95) an d DFAR 227.7202-3(a)DOCUMEN TATION IS PROVIDED “A S IS” WITH OUTWARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,INCLUDIN G BUT NOT LIMITED TO, ANY KIND O F IMPLIEDOR EXPRESS WARRANTY OF N ON -INFRINGEMEN T OR TH EIMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESSFOR A PARTICULAR PURPOSE.

Copyright 1998 Sun Microsystems, Inc.All rights reserved. Use issubject to license terms. Third-party software, includ ing fonttechnology, is copyrighted and licensed from Sun su pp liers. Sun,Sun Microsystems, the Sun Logo, Solaris, Java are trademark s orregistered tradem arks ofSun Microsystems, Inc.in the U.S. and other

countries. Use, du plication, or disclosure by the U.S. Govt is subjectto restrictions o f FAR 52.227-14(g)(2)(6/ 87) and FAR 52.227-19(6/ 87),or DFAR 252.227-7015(b)(6/ 95) and DFAR 227.7202-3(a)

Copyrigh t 1998 Sun Microsystems, Inc., 901San Antonio Road, PaloAlto, Californie 94303 Etats-Unis. Tous droits réservés.

Ce produ it ou do cument est protégé par un copy right et distribuéavec des licences qui en restreignent l’utilisation, la copie, ladistribution, et la décomp ilation. Aucun e partie de ce produ it oudocument ne peu t être reproduite sous aucune forme,p ar quelquemoyen qu e ce soit, sans l’au torisation p réalable et écrite de Sun et de

ses bailleurs de licence, s’il y en a. Le logiciel dét enu p ar des tiers, etqui comprend la technologie relative aux p olices de caractères, estprotégé par u n copyright et licencié par d es fourn isseurs de Sun.

Sun, Sun Microsystems, le logo Sun , Solaris, Java, JavaSoft, JavaMail,JavaBeans, JDK sont des marques de fabrique ou des marquesdép osées de Sun Microsystems, Inc.au x Etats-Unis et dans d’autrespays. L’interface d’utilisation grap hique OPEN LOOK et Sun ™ a étédévelopp ée par Sun Microsystems, Inc.p our ses utilisateurs etlicenciés. Sun reconnaît les efforts de pionniers de Xerox pour larecherche et le développem ent du concept des interfaces

d’utilisation visuelle ou grap hique p our l’ind ustrie del’informatique. Sun d étient une licence non exclusive d e Xerox surl’interface d’utilisation graph ique Xerox,cette licence couvran tégalem ent les licenciés de Sun qui metten t en place l’interfaced’utilisation graphiqu e OPEN LOOK et qui en outre se conformentaux licences écrites de Sun.L’accord du gouvernement américain estrequis avant l’exportation du p rodu it.

LA DOCUMEN TATION EST FOURNIE “EN L’ETAT” ET TOUTESAUTRESCONDITIONS,DÉCLARATIONSETGARANTIES

EXPRESSES OU TACITES SONT FORMELLEMENT EXCLUESDAN S LA MESURE AUTORISÉE PAR LA LOIAPPLICABLE, YCOMPRISNOTAMMENTTOUTEGARANTIEIMPLICITERELATIVE À LA QUALITÉMA RCHANDE, À L’APTITUDE À UN EUTILISATION PARTICULÈRE OU À L’ABSENCE DECONTREFAÇON.

Copyrigh t 1998Sun Microsystems, Inc.Tous droits réservés.Distribu é pa r des licences qu i en restreignen t l’utilisation. Le logicieldétenu p ar des tiers, et qui comprend la technologie relative aux

polices de caractères, est protégé par u n copyright et licencié par d esfournisseurs de Sun . Sun, Sun Microsystems, le logo Sun, Solaris,Java sont des marqu es de fabrique ou d es marques dép osées de SunMicrosystems, Inc.au x Etats-Unis et dans d’autres pays.

PleaseRecycle

Page 3: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 3/37

ii i

  A ugust 1998 JavaM ail Guide for Service Providers

ContentsChapter 1: Introduction 1

Chapter 2: Messages 3

The Structure of a Message 3

Simple Messages 4

Multipart Messages 4Messages and the JavaBeans Activation Framework 5

The DataSource 6

The DataContentHandler 6

Message Subclasses 7

Creating a Message Subclass 7

Message Attributes 7

Setting Message Content 8Accessing Message Content 8

Creating a MimeMessage Subclass 9

Creating the Subclass 9

Headers 10

Content 12

Special Cases: Protocols that Provide Preparsed Data 13

Chapter 3: Message Storage and Retrieval 15

Store 15

Authentication 15

The protocolConnectMethod 16

The connect Method 16

Folder Retrieval 16

Folders 17Folder Naming 18

Folder State 18

Messages Within a Folder 19

Getting Messages 20

Searching Messages 21

Getting Message Data in Bulk 22

Folder Management 23Appending and Copying Messages 23

Expunging Messages 23

Page 4: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 4/37

iv Contents

  A ugust 1998 JavaM ail Guide for Service Providers

Hand ling Message Flags 24

Chapter 4: Message Transport 25

Transport 25

The sendMessage Method 25

The protocolConnectMethod 26

Address 27

Chapter 5: Events 29

Chapter 6: Packaging 31

Page 5: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 5/37

1

  A ugust 1998 JavaM ail Guide for Service Providers

Chapter 1:

 Introduction

JavaMail provides a common, uniform API for managing electronic mail. It allowsservice-providers to provide a standard interface to their standards-based or

proprietary messaging systems u sing the Java p rogramming language. Using th isAPI, applications access message stores, and compose and send messages.

FIGURE 1-1

The JavaMail API is comp osed of a set of abstract classes that m od el the variou spieces of a typ ical mail system. These classes include,

s Message—Abstract class that rep resents an electronic mail m essage.JavaMail implements the RFC822 and MIME Internet messaging standards. TheMimeMessage class extend s Message to rep resent a MIME-style email message.

s Store—Abstract class that represents a database of messages maintained by amail server and grouped by own er. A Store uses a part icular access protocol.

s Folder—Abstract class that provid es a wa y of hierarchically organizing m essages.Folders can contain messages and other folders. A mail server provides each

user with a default folder, and users can typically create and fill subfolders.s Transport—Abstract class that represents a specific transport protocol. ATransport object u ses a particular transport protocol to send a message.

As a service provider, you imp lement abstr act classes in term s of your sp ecificprotocol or system. For example, an IMAP provider implements the JavaMail APIusing th e IMAP4 protocol. Clients then use you r imp lementation to manipu late theirelectronic mail.

Mail

JavaMail Client

Mail Server

Network 

Page 6: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 6/37

2 Chapter 1: Introduction

  JavaM ail Guide for Service Providers A ugust 1998

FIGURE 1-2 shows a client using an IMAP4 implementation to read m ail, and anSMTP implementation to send mail. (They can be from th e same or d ifferent vend ors.)

FIGURE 1-2

This Service Provider’s Guide shows you how to develop and package a JavaMailservice provider for your clients. It is meant to be used in conjunction with theJavad oc provid ed with the JavaMail API and the JavaMail API Specification.

This guide covers:

s Creating messages

s Storing and retrieving messages

s Sending a m essage

s Communicating with a client (for example, notifying the client of new mail)

s Packaging your implementation

The descriptions of the first three tasks show h ow to su bclass the app ropr iate abstractclasses and implement their abstract methods. In addition, the task descriptions point

out the m ethods that have d efault implementations that you m ight choose to overridefor the sake of efficiency.

SMTP

Abstract Classes

Implementation: Implementation:

Transport, Store, Folder...

SMTPTransport... IMAPStore,IMAPFolder...

IMAP

JavaMail Client

Calls forsending mail

Calls forreading mail

Mail Server

Destination

SMTP

Page 7: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 7/37

 3

  A ugust 1998 JavaM ail Guide for Service Providers

Chapter 2:

 M essages

Messages are central to an y electronic mail system. This chapter d iscusses h ow toimplement them for your p rovider.

If your provid er allows only for the common case of creating and send ing MIME stylemessages, then your provider can use the pre-written JavaMail messageimplementation: the javax.mail.internet .MimeMessage class. Implementationsthat furnish a protocol like SMTP fall into this category.

If your implementation does not fall into the previous category, you will have toimplement your own Message subclass. This chap ter

s Explains the structure of a Message object

s Explains how Message objects use the JavaBeansTM Activation Framework

s Shows you h ow to d evelop a Message subclass

The Structure of a M essageThe Message class models an electronic mail message. It is an abstract class that

implements the Part interface.

The Message class defines a set of attributes and content for an electronic mailmessage. The attributes, which are n ame-value pairs, specify add ressing informationand define the structure of the message’s content (its content type). Messages cancontain a single content ob ject or, indirectly, multiple content objects. In either case, thecontent is held by a DataHandler object.

Page 8: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 8/37

4 Chapter 2: M essages

The Structureof a Message

  JavaM ail Guide for Service Providers A ugust 1998

Sim ple M essages

A simple message has a single content object, which is wrapped by a DataHandlerobject. FIGURE 2-1 shows th e structure of a Message object:

FIGURE 2-1 Stru cture of a Simp le Message

  Multipart Messages

In add ition to the simp le structure shown in FIGURE 2-1, messages can also containmu ltiple content objects. In this case the DataHandler object contains a Multipart

object, instead of merely a a sing le block of content d ata.

A Multipart object is a container of BodyPart objects. The structu re of a BodyPartobject is similar to the structure of a Message object, because they both implement thePart interface.

Each BodyPart object contains attributes and content, but the attributes of aBodypart object are limited to those defined by the Part interface. An importantattribute is the content-type of this part of the message content. The content of aBodyPart object is a DataHandler that contains either d ata or anoth er Multipartobject. FIGURE 2-2 on page 5 shows th is structure.

Message Class

Header Attributes 

Content Body 

Attributes, such as

Content-Type.

DataHandler Object 

Contains data that conforms

to the Content-Type attribute

Page 9: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 9/37

Chapter 2: M essages 5

 M essages and the JavaBeans Activ ation Framework 

  A ugust 1998 JavaM ail Guide for Service Providers

FIGURE 2-2 Structure of a Message with Multiple Content Types

 Messages and the JavaBeans A ctivation Framework As shown in FIGURE 2-1 on page 4, the content of a message is represented by aDataHandler object. The DataHandler class is p art of the JavaBeans ActivationFramework (JAF). Documentation on the JAF can be obtained from the world-wideweb athttp://java.sun.com/beans/glasgow/jaf.html .

The DataHandler class provides a consistent interface to data, independent of itssource and format. The data can be from message stores, local files, URLs or objects inthe Java program ming langu age.

Multipart Object

Header Attributes 

Content Body 

Message

Header Attributes 

Content Body 

Message

attributes, with a

content type of

Multipart.

Contains a

Multipart object

instead of data

Contains either data, or

another Multipart

object.

Attributes from the

Part interface,such as this part’s content

type

BodyPart Object

A Multipart Message can holdmore than one BodyPart Object.

BodyPart Object 

DataHandler Object 

DataHandler Object 

Page 10: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 10/37

6 Chapter 2: M essages

 M essages and the JavaBeans A ctiv ation Framework 

  JavaM ail Guide for Service Providers A ugust 1998

The DataSource

A DataHandler object accepts data in the form of an object in the Java programminglangu age d irectly. For dat a from message stores, files or URLs, however, aDataHandler depend s on objects that imp lement the DataSource interface toprovide data access. A DataSource object p rovides access to d ata in th e form of aninpu t stream.The DataSource interface is also part of the JAF. JavaMail provides thefollowing DataSource objects:

s javax.mail.MultipartDataSource

s javax.mail.internet.MimePartDataSource

The DataContentHandler 

DataHandler objects return the content of a message as an ob ject in the Javaprogramming language. They use objects that implement the DataContentHandler

interface to translate message content between the streams provided by DataSource

objects and objects in the Java programming language. The getContent an dwriteTo methods of the text/ plain DataContentHandler show this:

public class text_plain implements DataContentHandler {

// This method creates a String from a “text/plain”

// data source

 public Object getContent(DataSource dataSource) {InputStream inputStream = dataSource.getInputStream();

ByteArrayOutputStream outputStream =

new ByteArrayOutputStream();

int c;

while ((c = inputStream.read()) != -1)

outputStream.write(c)

// get the character set from the content-type

String charset = getCharSet(dataSource.getContentType());

return new String(outputStream.toByteArray(), charset);

}

// This method creates a byte stream from a String

 public void writeTo(Object object, String type,

OutputStream outputStream) {OutputStreamWriter writer =

new OutputStreamWriter(outputStream, getCharset(type));

String string = (String)object;

writer.write(string, 0, string.length());

writer.flush();

}

}

Page 11: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 11/37

Chapter 2: M essages 7  

 M essage Su bclasses

  A ugust 1998 JavaM ail Guide for Service Providers

DataContentHandlers are also part of the JAF. The JavaMail implementation in thecom.sun.mail.handlers package includes DataContentHandlers for the

following two MIME types:s multipart/mixed (the nam e of the class is multipart_mixed)

s text/plain (the nam e of the class is text_plain)

A DataHandler typ ically find s th e correct DataContentHandler for a particularMIME type through the MailCap registry. (The client programmer can also providethe correspondence programmatically.)

 M essage SubclassesThe following factors determine the message class of your provider:

s If app lications will use your p rovider for interacting with a n on-MIME messagingsystem, create a subclass of the Message class (See “Creating a MessageSubclass” on pag e 7.)

s If applications will use your provider to interact with a message store thatsup port s MIME messages, create a subclass of the MimeMessage class. (See“Creating a Mim eMessage Subclass” on p age 9.)

s If app lications will use your p rovider to send MIME messages then use theMimeMessage class without subclassing it.

Creating a Message Subclass

When you subclass the Message class, you m ust implement m ethods that man ageattributes, that retrieve content, and that set content.

 Message A tt ribut es

Your implementation is expected to support the attributes in the Message class andits Part interface by implementing their get an d set method s. If your m essaging

system does not allow the modification of an attribute, have the method that sets itthrow the IllegalWriteException .

In add ition to supp orting the p redefined attributes, you can also expose attributesspecific to your imp lementation. To make a system -specific attribute av ailable in you rsubclass, add a field that represents the attribute and provide accessor methods for it.

Page 12: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 12/37

8 Chapter 2: M essages

 M essage Su bclasses

  JavaM ail Guide for Service Providers A ugust 1998

Setting M essage Cont ent 

The Message class provides a number of abstract methods for setting messagecontent. These will be used by clients preparing an outgoing message.

Some m ethods take m essage data directly, and expect your imp lementation to wrapthe data in a DataHandler object:

public void setContent(java.lang.Object obj,java.lang.String type)

public void setText(java.lang.String text)

To wrap the d ata, use the DataHandler constructor that requ ires an object and a datatype. You can then call the same method that clients call when they have wrappedtheir data in a DataHandler object themselves:

public void setDataHandler(javax.activation.DataHandler dh)

This method is abstract.

 Accessing Message Content 

The Message class provides three methods for getting the message content:

s public javax.activation.DataHandler getDataHandler()

s public java.lang.Object getContent()

s public java.io.InputStream getInputStream()

They are used b y clients to get a message from a folder. To imp lement th ese method s:

1. Optional: provide a cache for the DataHandler object

Caching the DataHandler can improv e performan ce if it reduces the num ber of times you must access the store.

public MyMessage extends Message {

// field for caching the data handler

private DataHandler dh;

...

}

2. Implement the abstract getDataHandler method

Return th e approp riate DataHandler object. For example:

public MyMessage extends Message {

... public DataHandler getDataHandler() throws MessagingException {

if (dh == null)

dh = new DataHandler(new SomeDataSource(this));

return dh;

}

}Note that you mu st provide a DataSource object to the DataHandler. For example,th e MimeMessage subclass uses the MimePartDataSource class.

Page 13: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 13/37

Chapter 2: M essages 9

 M essage Su bclasses

  A ugust 1998 JavaM ail Guide for Service Providers

3. Have the getInputStream and getContent methods de legate to the JAF.

Implement the getInputStream an d getContent method s to call thecorresponding DataHandler method s. For examp le:

public InputStream getInputStream () throws IOException {return getDataHandler().getInputStream();

}

public Object getContent() throws IOException {return getDataHandler().getContent();

}

Using the techniques described above ensures that you make proper use of the JAF.The javax.mail.internet package is implemented this way.

Creating a MimeMessage Subclass

The javax.mail.internet package provides a comp lete imp lementation of theinternet standards that define the structure of an email message: RFC822 and MIME(RFC2045 - 2047). It defines a subclass of the Message class called MimeMessage. The

MimeMessage class adds:1. Method s to get an d set MIME-specific attributes.

2. The ability to parse a MIME-style input stream into its header and content.

3. The ability to generate a MIME-style bytestream.

This section explains enough about the MimeMessage class and thejavax.mail.internet package to enable you to implement a subclass of MimeMessage. The up coming sections use a POP3 implementation, POP3Message,as an example.

Creatin g the S ubclass

A new ly created m essage, wh en it represents a message from a message store, shou ldbe a lightweight object that is filled with data only as that data is required. Yourconstructor, therefore, shou ld create a message object tha t d oes not immed iately loadits data. For example:

public class POP3Message extends MimeMessage {

// Keep track of whether data has been loaded

boolean loaded = false;

...

 public POP3Message(POP3Folder folder, int messageNumber) {

// This MimeMessage constructor returns an empty message object

super(folder, messageNumber);}

...}

Page 14: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 14/37

10 Chapter 2: M essages

 M essage Su bclasses

  JavaM ail Guide for Service Providers A ugust 1998

Objects that retu rn m essages, such as folders, can u se this constructor. For example,the folder class that is par t of the POP3 service provider, POP3Folder, could get a

particular POP3 message:public Message getMessage(int messageNumber) {

POP3Message message;

...

 message = new POP3Message(this, messageNumber);

...

return message;

}

The next sections, which discuss how to manage Message headers and content,describe a way to load the m essage’s data on deman d.

 Headers

The MimeMessage constructor holds its h eaders in ajavax.mail.internet.InternetHeaders object. This object, when constructedwith an InputStream, reads lines from th e stream u ntil it reaches the blank line th at

ind icates end of head er. It stores the lines as RFC822 head er-fields. After th eInternetHeaders object reads from the inp ut stream , the stream is positioned at th estart of the message body.

The POP3 imp lementation u ses this constructor to load the m essage headers w henone is requested:

public class POP3Message extends MimeMessage {//Keep track of whether the Message data has been loadedboolean loaded = false;

int hdrSize;...

public String[] getHeader(String name) {//Get the headers on demand from the message storeload();// Don’t need to reimplement getting the header object’s contentsreturn super.getHeader(name);

}

/*** Reimplement all variants of getHeader() as above ***/

...

 private synchronized void load() {if (!loaded) {// Get message data (headers and content) and cache itcontent = POP3Command(“RETR”, msgno);// Open a stream to the cacheInputStream is = new ByteArrayInputStream(content);// Setup “headers” field by getting the header dataheaders = new InternetHeaders(is);// Save header size to easily access msg content from cachehdrSize = content.length - is.available();loaded = true;

Page 15: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 15/37

Page 16: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 16/37

Page 17: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 17/37

Chapter 2: M essages 13

 M essage Su bclasses

  A ugust 1998 JavaM ail Guide for Service Providers

}...

private synchronized void load() {if (!loaded) {

// Get message data (headers and content) and cache it

content = POP3Command(“RETR”, msgno);

// Open a stream to the cache

InputStream is = new ByteArrayInputStream(content);

// Setup “headers” field by getting the header data

headers = new InternetHeaders(is);

// Save header size to easily access msg content from cache

hdrSize = content.length - is.available();

loaded = true;}

}

}

When clients call the POP3Message class’s getDataHandler, getContent, o rgetInputStream method s of a MimeMessage, the bytes th ey receive are alreadydecoded.

 Mu ltipart M IME M essages

As discussed in “The Stru cture of a Message” on p age 3, messages can have a singlecontent object or, indirectly, multiple content objects. The DataHandler of aMIME multip art m essage contains an object of class MimeMultipart from thejavax.mail.internet package. Invoking the getContent method on a MIMEmultipart message typically returns this class.

You typ ically do n ot hav e to subclass the MimeMultipart class. The multipart

DataContentHandler provided by the com.sun.mail.handlers package createsthis object internally wh en it is given a DataSource. It is directed to d o so by th is entryin m ailcap file in the JavaMail distribut ion:

multipart/*;; x-java-content-handler=\

com.sun.mail.handlers.multipart_mixed

Note th at classes in th e com.sun.mail package, and its subpackages, are not part of the JavaMail API. They are sepa rate imp lementations of the API.

Special Cases: Protocols that Provide Preparsed Data

Some protocols, such as IMAP, provide preparsed data. In this case, you overridemost MimeMessage method s to avoid p arsing the inpu t stream. A MimeMessage

subclass for a protocol like IMAP acts like an interface that mod els the MIME API.

For example, if multipart IMAP content is retrieved in the same way as multipartMIME content , the DataContentHandler re-parses the mu ltipart d ata that has

already been p arsed at the server. To avoid the extra p arse, you create a special type of 

Page 18: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 18/37

14 Chapter 2: M essages

 M essage Su bclasses

  JavaM ail Guide for Service Providers A ugust 1998

DataSource - the MultipartDataSource , and pass that to the DataHandler. TheDataHandler passes it on to the MultipartDataContentHandler, which avoids

the parse if it's DataSource is already of type MultipartDataSource .So, an IMAPMessage's getDataHandler() method may be:

public javax.activation.DataHandler getDataHandler()

throws MessagingException {

if (dh != null)

return dh;

if (myType.equals("multipart")) {

dh = new DataHandler(new IMAPMultipartDataSource(this));

} else {dh = new DataHandler(new IMAPDataSource(this));

}

return dh;

}

The IMAPMultipartDataSource is a sub class of MultipartDataSource .

15

Page 19: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 19/37

15

  A ugust 1998 JavaM ail Guide for Service Providers

Chapter 3:

 M essage Storage and Retrieval

Users interact with message stores to fetch and manipulate electronic mail messages.This chap ter d iscusses how to imp lement t he classes that allow clients th is access. If you a re creating a JavaMail service provid er that allows a client to send m ail, but doesnot interface with a mail store, you do not have to implement this functionality.

To provide message storage and retrieval, you must implement some abstract classes:

s Store, which mod els the message database and the access protocol used toretrieve messages. Its implementation is discussed in “Store” on pag e 15.

s Folder, which represents a n ode in th e message storage hierarchy u sed toorganize messages. Its implementation is discussed in “Folders” on p age 17.

StoreThe Store class mod els a message da tabase and its access protocol. A client u ses it toconnect to a particular message store, and to retrieve folders (groups of messages).

To provide access to a message store, you must extend the Store class an dimplement its abstract method s. In ad dition, you mu st override th e defaultimplementation of at least one method that handles client authentication. The nextsections cover how to write these methods. They begin with authentication, since itprecedes retrieval wh en the p rovider is used.

 Authentication

JavaMail provides a framework to su pp ort both the m ost comm on style of 

authentication, (username, passphrase), and other more sophisticated styles such as achallenge-response dialogue with the user. To furnish the (username, passphrase)style authentication in your provider, override the protocolConnect meth od . Touse another style of authentication, you mu st override the v ersion of the connect

method that takes no arguments.

16 Chapt er 3: Message S t orage an d Ret riev al

Page 20: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 20/37

16 Chapt er 3: Message S t orage an d Ret riev al

Store

  JavaM ail Guide for Service Providers A ugust 1998

The protocolConnect Method 

The Store class provid es a set of method s that establish a connection w ith a messagestore. Establishing a connection typically involves setting u p a n etwork connection toa host and authenticating th e user w ith the m essage store installed on that host. TheprotocolConnect method hand les these tasks.

The signature of the protocolConnect method is:

boolean protocolConnect(String host, int port,

String user, String password)

The method returns true if the connection and authentication succeed. If theconnection fails, it th rows a MessagingException . If the au thentication fails, itreturns false.

The default implementation of protocolConnect returns false, ind icating that th eauthentication failed. You should provide an implementation that connects to thegiven host at th e specified po rt, and performs the service-specific authent ication u singthe given username and passphrase. The simplest implementation, for message storesthat d o not require authentication, merely has this method return true. An example

of such a m essage store is one th at is local file-based.Note that clients do not call the protocolConnect method directly. Instead, theprotocolConnect method is invoked when clients call one of the connect

methods

The connect Method 

To provide authentication schemes more sophisticated than (username, passphrase),you m ust override the version of the connect method that takes no arguments.

The connect method takes no arguments and uses an Authenticator object toobtain information from the user if the information is not already available. (Theclient provides the Authenticator object.)

It then uses that information to connect to the message store and authenticate theuser. Finally, if the connection is successful, it delivers an OPENED

ConnectionEvent . (For more information about events, see Chap ter 5: Events.)

Folder Retrieval

A message store stores messages, and often allows users to further group theirmessages. These groups of messages are called folders, and are represented by theabstract class, Folder. The Store class provides abstract methods for allowing theuser to retrieve a folder:

s getDefaultFolders getFolder

Chapt er 3: Message S t orage an d Ret riev al 17

Page 21: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 21/37

Chapt er 3: Message S t orage an d Ret riev al 17  

Folders

  A ugust 1998 JavaM ail Guide for Service Providers

If you are un familiar with folders, please read “Folders” on p age 17 before continu ingwith this section.

The getDefaultFolder method mu st return th e default folder. The returned foldermu st be in a closed state. (This is the d efault initial state of a folder.)

The getFolder methods return the specified folders:

s Folder getFolder(String name)

s Folder getFolder(URLName urlname)

These method s return the requested folders w hether or n ot they exist in th e store.

(This is similar to t he java.io.File API.) Do not validate t he folder ’s existence inth e getFolder methods.

The folders returned by the getFolder methods must be in a closed state. (Thedefault initial state of a folder is closed.)

Note – The Store object should not cache Folder objects. Invok ing the getFolder

method mu ltiple times on the same folder name mu st return that many d istinctFolder objects.

FoldersThe Folder class mod els a nod e in a m ail storage hierarchy. Folders can containmessages or subfolders or both. FIGURE 3-1 illustrates this.

FIGURE 3-1 Message Store containing Folders

Each user has a folder that has the case-insensitive name INBOX. Providers m ustsup por t this nam e. Folders hav e two states: they can be closed (operations on a closedfolder are limited) or open.

Store

User1 User2

Inbox Inbox Personal

Mom

Folder

User...

Message Store

represented

in User2’sclient

in User2’sclient

18 Chapt er 3: Message S t orage an d Ret riev al

Page 22: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 22/37

18 Chapt er 3: Message S t orage an d Ret riev al

Folders

  JavaM ail Guide for Service Providers A ugust 1998

Since Folder is an abstract class, you must extend it and implement its abstractmethod s. In ad dition, some of its methods have d efault implementations that,

depend ing on your system, you m ay want to override for performance pu rposes. Thissection covers many of the abstract m ethods that you mu st implement, and themethod s whose d efault implementations you m ight want to override. It groups th emin the following way:

s “Folder N aming”: getName, getFullName, getSeparator

s “Folder State”: open, close

s “Messages Within a Folder”: getMessage, getMessages, search, fetch

s “Folder Management”: getPermanentFlags , setFlags, appendMessages,copyMessages, expunge

Folder Naming

Each folder has a name. One such name is INBOX; You m ust sup port that n ame in acase-insensitive fashion. Typically, mail system s allow users to create and nam e other

folders for organizing their m essages, leading to a tree-like organization of electronicmail in the message store.

The Folder class has two abstract m ethods that return th e nam e of a folder:

s getName

s getFullName

A folder ’s full name is the combination of its nam e and its ancestors’ nam es. Eachlevel in the hierarchy of the folder’s full name is separated from the next by the

hierarchy delimiter character. The hierarchy delimiter character is returned by themethod getSeparator.

The getSeparator meth od is an abstract method ; imp lement it to return a Folder ’shierarchy delimiter. If your message store does not support a hierarchical storagestructure, the getSeparator method mu st return the NUL character (\u0000).

Folder State

Folders can be in one of tw o states: open or closed . Initially a folder is closed. Theoperations allowed on a closed folder are limited; in particular, very few messagerelated operations are allowed. Having the initial state of folders be closed allowsthem to be created as light-weight objects, with no dedicated server connectionrequired. For example, an IMAP provider can designate a single server connection asthe “comm on” conn ection for all closed folders.

Folders are opened u sing the method:

public abstract void open(int mode)

Chapt er 3: Message S t orage an d Ret riev al 19

Page 23: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 23/37

p g g

Folders

  A ugust 1998 JavaM ail Guide for Service Providers

wh ere mode is either READ_ONLY or READ_WRITE. These mod es have the intuitivemeanings: only a folder opened in READ_WRITE mod e can be mod ified. If this folder

is opened successfully, you must deliver an OPENED connection event.The effect of open ing m ultiple conn ections to the sam e folder on a sp ecific Store isimplementation-dependent. You can choose to allow multiple readers but only onewriter, or you could allow multiple writers as well as readers.

Once a folder is open, a va riety of message-specific method s, such as getMessage,can be invoked on it. Implement the open method such that these operations can besuccessfully conducted after the method returns. For example, an IMAP provider

might want to open a new connection to the server and issue the SELECT commandto select this folder.

Open folders can be closed w ith the method :

public abstract void close(boolean expunge)

The close method on an open folder typically has th e Folder object get rid of itsmessage-cache, if it main tains on e, and generally reset itself, so that its a light-weightobject again. Invok ing th e close method on a closed folder shou ld not h ave any

effect.The close method must indicate that the folder is closed even if it terminatesabnormally by throwing a MessagingException . That is, you mu st still deliver aCLOSED connection event and make the Folder object such tha t calls to th e isOpenmethod return false.

 Messages Within a Folder 

Folders can be viewed as presentin g a resizable array of messages to a client. Theyallow the client to access a message based on its ind ex within th is array. The ind ex isthe message’s sequence-number. Sequence numbers begin at one (1) and continue,incrementing by one, through the total number of messages in the folder. A Folder

imp lementation typ ically employs a su itable collection class, such as Vector, to storemessages.

This section discusses the abstract methods that the Folder class p rovides to clients

for retrieving messages and the information they contain. It groups these methods asfollows:

s “Getting Messages”

s “Searching Messages”

s “Getting Message Data in Bulk”

20 Chapt er 3: Message S t orage an d Ret riev al

Page 24: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 24/37

Folders

  JavaM ail Guide for Service Providers A ugust 1998

Getting Messages

The Folder class provides two methods to get one or more messages from a folder:getMessage an d getMessages.

The getMessage Method 

The signature of the getMessage method is:

public abstract Message getMessage(int index)

Note that the getMessage method is abstract; you mu st provide an im plementation

for it. It returns the Message object with the given sequence number. Messagenumbers begin at one (1).

It is important th at your imp lementation of the getMessage method d oes not returna completely filled (also called a heavy-weight ) Message object. The client’sexpectation is that a Message object is just a “reference” to t he m essage, so insteadyou shou ld create Message objects that are almost em pty (also called light-weight 

messages). The client w ill fill it as content is need ed by th e user. For examp le, anIMAP imp lementation migh t create IMAPMessage objects that initially contain onlythe appropriate IMAP Sequence number or IMAP UID.

The getMessages Methods

The getMessages method s have the following signatures:

public Message[] getMessages()

public Message[] getMessages(int[] msgnums)

public Message[] getMessages(int start, int end)

The getMessages method s have default imp lementations that use getMessage toreturn the requested messages. The getMessages method, when given noparam eters, returns all of the Message objects in the folder.

Note – Folder implementations should cache Message objects. This insu res tha t if aclient calls the getMessage method mu ltiple times, the implementation w illefficiently retu rn the sam e Message object unless the client calls the expunge

method.

Clients that use message-numbers as their references to messages will invoke thegetMessage method quite often to get at the app ropriate Message object. Creating anew Message object each tim e, instead of caching th e messages, wou ld be exp ensivein terms of memory an d time.

Chapt er 3: Message S t orage an d Ret riev al 21

Page 25: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 25/37

Folders

  A ugust 1998 JavaM ail Guide for Service Providers

Searching Messages

TheFolder

class provides search m ethods th at return the m essages that m atch th egiven search criteria. The signatu res of the meth ods are show n below. The firstsearch method shown, w hich takes only a SearchTerm argum ent, applies thesearch criteria to each message in th e folder. The second search method shownapp lies the search criteria to th e specified m essages.

Message[] search(SearchTerm term)

Message[] search(SearchTerm term, Message[] msgs)

Default imp lementations are p rovided for both search method s. The d efault

implementations do client-side searching by applying the given SearchTerm on eachMessage and returning those messages that match.

If your message store supports server-side searching, you can override the defaultimplementation to take advantage of it. Your implementation should

1. Construct a search express ion correspo nding to the SearchTerm provided.

The client uses SearchTerm objects to constru ct a tree of terms that rep resent asearch criteria. For examp le, the tree show n in FIGURE 3-2 represents a search formessages from “manager” that contain the word “deadline” in the subject.

FIGURE 3-2 Samp le Search Tree

Traverse the search-tree specified by the given SearchTerm to constru ct the searchexpression for the server-side search.

2. Use the constructed search expression on the server.

For example, an IMAP p rovider w ill convert the SearchTerm in to an IMAP searchsequence and pass it on to the IMAP server.

If the SearchTerm is too complex, or contains a sub class of the SearchTerm classthat the client has defined, you can either throw a SearchException or use thedefault im plementation of client-side searching by calling super.search

AndTerm

FromTerm SubjectTerm

manager deadline

22 Chapt er 3: Message S t orage an d Ret riev al

F ld

Page 26: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 26/37

Folders

  JavaM ail Guide for Service Providers A ugust 1998

3. The Message objects returned by the search methods should be “light-weight”

messages.

To repeat th e examp le on page 20, an IMAP implementation might returnIMAPMessage objects that initially contain on ly the ap prop riate IMAP Sequen cenumber or IMAP UID.

Getting Message Data in Bulk 

As mentioned in the previous sections, a Message object should start out as a light-weight reference to the correspond ing m essage. The client inv okes meth ods t o fill in

the m essage as the d ata is required.

To h elp d eliver m essage content, certain server-based m essage access protocols, suchas IMAP, allow batch fetching of message attribu tes for a ran ge of messages in asingle request. The Folder class provid es a fetch method to allow service providersto take advantage of this capability; check your service provider’s documentation.

The fetch method takes an array of Message objects and a FetchProfile object asarguments. Its signature is:

public void fetch(Message[] msgs, FetchProfile fp)

The FetchProfile object lists the message attributes to be obtained for themessages. The fetch method , if a service provider su pp orts getting m essage data inbulk, gets the requested attributes and stores them in the Message objects.

If you r access protocol allows b atch fetching of message attribu tes, then you shou ldoverride this method to allow clients to take advantage of it. The defaultimplementation of the fetch method returns without doing any work.

When clients call the fetch method, they provide a FetchProfile with the namesof the items to be obta ined. The items can be p re-d efined FetchProfile attributes,the names of header-fields, or both. The currently defined attributes are:

s ENVELOPE–This includes the common “toplevel” attributes of a message. Theseare gen erally th e ma in ad dressing a ttribu tes - From, To, Cc, Bcc, Reply-To, Subjectand SentDate. GUI Mailers usually display a subset of these items in header-listwind ow, so a p rovider mu st attempt to includ e at least these items. For example,

an IMAP provider w ill include th e ENVELOPE data item.s CONTENT_INFO–This specifies informa tion abou t the conten t of the message,

including the ContentType, ContentDisposition, Size and LineCount. Forexample, an IMAP provider will include the BODYSTRUCTURE data item.

s FLAGS–This specifies the flags for a message. (More information on flags isprovided in “Handling Message Flags.”)

Your implementation of the fetch method should support the FetchProfile

attributes appropriate for your system.

Chapt er 3: Message S t orage an d Ret riev al 23

Folders

Page 27: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 27/37

Folders

  A ugust 1998 JavaM ail Guide for Service Providers

Folder M anagement 

This section discusses the abstract methods that the Folder class prov ides to clientsfor manipulating a group of messages in a folder. It groups these methods as follows:

s “Appending and Copying Messages”s “Expunging Messages”s “Handling Message Flags”

 Appending and Copying Messages

The Folder object provides an abstract appendMessages meth od. Yourimp lementation shou ld ad d th e given messages onto the end of this folder ’s messagesand deliver a MessageCountEvent if possible. Note that the ap pend operation isvalid on a closed folder.

Some or all of the Message objects might belong to the same Store as this Folder.If your system can optimize the append operation by doing server-side copies, youmight want to check for and handle this special case.

The copyMessages method copies the specified messages from this folder to thedestination folder. There is a default implementation for this method that uses theappendMessages method to do the copy. If your system supports server-side copy,make su re that this operation emp loys that optimization, either by overriding thismethod or by implementing the appendMessages method to hand le this case.

  Expunging Messages

The Folder object provides an abstract expunge method . Your implementation shou ld:s Remove all messages that are marked deleted (i.e, have their DELETED flag set)

from the folder and set the values of those messages’ expunged fields to tru e.

s Renum ber the m essages in the folder th at occur after an expu nged message sothat their sequence numbers match their index within the folder. For example, if messages A and C are removed du e to the expunge method being invoked, theremaining messages (B, D and E) are renu mbered suitably, as FIGURE 3-3 shows.

FIGURE 3-3 Message Renumbering After Expunging

s Send one or more MessageCountEvents to notify listeners abou t the remova l of 

the messages. When you call the notifyMessageRemovedListeners method,its boolean argument, removed, must be set to true.

A (1) B (2) C (3) D (4) E (5) Folder before invoking the expunge method

B (1) D (2) E (3) Folder after invoking the expunge method

24 Chapt er 3: Message S t orage an d Ret riev al

Folders

Page 28: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 28/37

Folders

  JavaM ail Guide for Service Providers A ugust 1998

Only the getMessageNumber an d isExpunged method s are valid on an expungedMessage object.

Some messaging systems support shared folders that can be accessed and modifiedfrom mu ltiple sessions at the same time. In su ch cases, multiple open Folder objectscan correspond to the same physical folder. An expunge operation on one of thoseFolder objects remov es all deleted m essages from the p hysical folder. How ever, theother folders m ust not  remove the correspond ing Message objects from their  lists.They should m ark those messages as expunged, so that any direct method on thoseMessages will fail. They may also fire MessageCountEvents (with the removedboolean flag set to false) to notify listeners about the rem oval. In essence, those

Folders will continue to p resent th e same, unchanged array of Messages to theirclients. The array is pu rged and messages are renumbered on ly when the expunge

method is directly invoked.

Refer to Section 6.2.3 in the JavaMail 1.1 Specification document for the rationale forthis behav ior.

 Handling Message Flags

Flags are indicators of message state stored with a message. The set of flags associatedwith a message is represented by a Flags object; ind ividu al flags are represented byth e Flags.Flag object. The flags rep resented by th e Flags.Flag class includ eANSWERED, DELETED, DRAFT, FLAGGED, RECENT, SEEN, and USER. (The USER flagmeans that this folder supports user-defined flags.)

The Folder class provides the getPermanentFlags method and the setFlagsmeth ods for hand ling flags. This section first covers the getPermanentFlags

method, then the setFlags methods.The getPermanentFlags method is abstract:

public abstract Flags getPermanentFlags()

Your implementation should return a Flags object th at contains every Flags.Flag

that your system supports.

The setFlags methods have default implementations to set the specified flags on agiven ran ge of messages. They set th e flags on each Message object individu ally(after obtaining the message by calling the getMessage method, if necessary) andsend the appropriate MessageChangedEvent .

Most message stores provid e a call in their API to efficiently set flags on a grou p of messages. If your system does this, consider overriding the default implementationsof the setFlags method s to m ake use of the server-side optimization.

If you override th e setFlags method s, be sure that the method s that operate onsequence-nu mbers d o not  abort the operation if any sequence-number refers to an

expu nged message. Instead of aborting, your implementation should continueoperating on the rest of the messages.

 25

Page 29: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 29/37

  A ugust 1998 JavaM ail Guide for Service Providers

Chapter 4:

 M essage Transport 

The JavaMail API provid es the ability for users to sen d electronic mail messages. Thischapter describes how to furnish a JavaMail service provider of a message transportsystem. If you are creating a JavaMail service provid er that allows a client to accessa mail server but d oes not handle sending m ail, you do n ot have to implement thisfunctionality.

To provide a message transport system, you m ust d o the following:

s Provide a Transport implementation (See “Transp ort” on page 25.)

s Provide an Address subclass (See “Add ress” on page 27.)

Transport The function of the Transport class is to send (transpor t) messages; it is an a bstractclass. To imp lement a sp ecific transp ort p rotocol:

s Subclass th e Transport class

s Implement the Transport class’s abstract m ethod , sendMessage

s Override the d efault imp lementation of the Transport class’sprotocolConnect method

The sendMessage Method 

The Transport class provides static meth ods tha t app lications use to send messages.The default implementations of these m ethods call the abstract m ethodsendMessage to d o the actual transm ission. The sendMessage method has thefollowing signature:

public abstractvoid sendMessage(Message m, Address[] address)

throws MessagingException

Use the following procedure to imp lement the sendMessage method:

26 Chapt er 4: M essage Tran sport  

Transport 

Page 30: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 30/37

p

  JavaM ail Guide for Service Providers A ugust 1998

1. Check the type of the given message.

Typically, a service provider han dles on ly certain typ es of messages. For example, an

SMTP provider typically sends MimeMessages. In th e face of an u nknow n m essagetype, you can have sendMessage either fail and throw a MessagingException , oryou can try to coerce it into a known type and send it.

2. Transmit the message.

Get the byte stream of the message, and transmit the m essage using its writeTomethod.

3. Send a TransportEvent .

The TransportEvent indicates the delivery status of the message. The possible eventtypes are MESSAGE_DELIVERED , MESSAGE_NOT_DELIVERED , andMESSAGE_PARTIALLY_DELIVERED . For information about events, see Chap ter 5: Events.

4. Throw an exception if the delivery is unsuccessful.

If the d elivery fails, comp letely or p artially, you m ust throw a suitableMessagingException or SendFailedException .

The protocolConnect Method 

The Transport class provides methods for applications to call that establish aconnection with a transport. The methods, called connect, have d efaultimplementations that establish a connection by calling the protocolConnect

method . You mu st override the protocolConnect method.

The signature of the protocolConnect method looks like this:

protectedboolean protocolConnect(String host, int port,

String user, String password)

The method returns true if the connection and authentication succeed. If theconnection fails, it th rows a MessagingException . If the au thentication fails, itreturns false.

The default implementation of protocolConnect returns false, ind icating that th e

authentication failed. You should provide an implementation that connects to thegiven host at the specified port, and performs the transport-specific authenticationusing the given username an d password.

Page 31: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 31/37

28 Chapt er 4: M essage Tran sport  

 Address

Page 32: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 32/37

  JavaM ail Guide for Service Providers A ugust 1998

 29

Page 33: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 33/37

  A ugust 1998 JavaM ail Guide for Service Providers

Chapter 5:

 Events

The Store, Folder an d Transport classes use events to commu nicate state chan gesto applications. The documentation for the methods of these classes specify whichevents to generate. A comp liant p rovider mu st broadcast these events.

To broadcast an event, call the appropriate notifyEventListeners method . Forexamp le, to man age MessageCountEvents for new mail notification, your Foldersubclass should call the notifyMessageAddedListeners(msgs) method. (It isbest to use the d efault imp lementations of the NotifyEventListeners methods,because they dispatch their events in an internal event-dispatcher thread. Using aseparate thread like this avoids deadlocks from breakage in the locking hierarchy.)

Every event generated by the Store, Folder an d Transport classes also has

associated addListener an d removeListener method s. Like thenotifyEventListeners method s, these methods already h ave usefulimplementations. A programm er using your service provider implementation callsthe appropriate addEventListener an d removeEventListener methods tocontrol wh ich ev ent n otifications are received.

Page 34: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 34/37

 31

Page 35: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 35/37

  A ugust 1998 JavaM ail Guide for Service Providers

Chapter 6:

Packaging

Provider software m ust be p ackaged for use by JavaMail clients. To do th is:

1. Choose a suitable name for your package

The recomm ended way of doing this is to reverse your compan y dom ain name, andthen add a suitable suffix. For example, Sun’s IMAP provider is namedcom.sun.mail.imap .

2. Make sure that your key classes are public

If you prov ide access to a m essage store, your Store subclass mu st be a public

class. If you provide a way to send messages, your Transport subclass mu st be apublic class. (This allow s JavaMail to instantiate you r classes.)

3. Bundle your provider classes into a suitably named jar file

The name of the jar file should reflect the p rotocol you are prov iding. For examp le,an NNTP provider may have a jar file nam ed nntp.jar. Refer to a suitable Javaprogramming language book for details on how to create jar files.

Because you r jar file must be included in an application’s classpath so that it canbe found by the application’s classloader, include the name of your jar file in thedocumentation for your provider. Mention that the application’s classpath should beup dated to include th e location of the jar file.

4. Create a regis try entry for the protocol y our implementation provides

A registry entry is a set of attributes th at d escribe your imp lementation. There are fiveattribu tes that d escribe a protocol imp lementation. Each attribu te is a nam e-value pairwh ose syntax is name=value. The attributes are separated by semicolons (;).

TABLE 6-1 on page 32 lists and describes the attr ibutes in a JavaMail resource file.

Page 36: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 36/37

Chapter 6: Packaging 33

Page 37: Javamail for Providers-150193

8/8/2019 Javamail for Providers-150193

http://slidepdf.com/reader/full/javamail-for-providers-150193 37/37

  A ugust 1998 JavaM ail Guide for Service Providers

The users or ad ministrators of a JavaMail application place your m app ing into th eaddress.map registry, either m anu ally or using a configu ration tool. As statedpreviou sly, a registry is comp rised of resource files. The nam e of the file that hold syour mapping is called javamail.address.map . JavaMail searches resource files inthe following order:

1. java.home/lib/javamail.address.map

2. META-INF/javamail.address.map

In the docum entation that you p rovide to users, provide your m app ing, and requestthat it be p laced in one of the tw o files listed above.


Recommended