1、JavaMail FrameWork for developing internet-based e-mail client applications原文:E-mail functionality is an important system requirement in areas such as e-commerce, customer care, work-flow management and unified messaging. In addition, some application architectures may need to support not only stand
2、ard mail protocols but also proprietary ones. If youre charged with the task of developing an e-mail client application in Java, you have a number of architectural and design options: building your own services layer to support multiple mail protocols, purchasing third-party components that provide
3、e-mail features or using JavaSofts JavaMail framework.This article focuses on the JavaMail framework for developing Internet-based e-mail client applications. The JavaMail API shields application developers from implementation details of specific mail protocols by providing a layer of abstraction de
4、signed to support current e-mail standards and any future enhancements. JavaMail increases a developers productivity by allowing the developer to focus on the business logic of an application rather than on mail protocol implementation. It provides a platform and protocol-independent means of adding
5、 e-mail client features to your applications. JavaMail version 1.1 is a standard Java extension and requires JDK/JRE 1.1.x or higher.Overview of Internet Mail ProtocolsBefore getting into the details of JavaMail, a quick overview of some messaging terms and Internet e-mail protocols (IMAP, POP, SMTP
6、) is in order. A message is described in terms of a header and content. A message header comprises information such as sender (from), recipient (to), and message ID (a unique message identifier). A messages content is the actual message body and can comprise multiple parts in the form of text and at
7、tachments, as shown in FigureFigure1:An e-mail client is used to transfer messages to and from an e-mail server, which is responsible for sending and receiving e-mail messages across the Internet. These servers store a users messages either permanently or until retrieved by an e-mail client.To devel
8、op an e-mail client you need to deal with protocols for sending and receiving messages. As shown in Figure 2, the common protocol for sending Internet e-mail messages is SMTP (Simple Mail Transfer Protocol). The original SMTP specification limited messages to a certain line length and allowed only 7
9、-bit ASCII characters. The MIME (Multipurpose Internet Mail Extensions) specification builds on SMTP by removing the maximum line length for messages and allowing new types of content (e.g., images, binary files) to be included in e-mail messages. The MIME specification overcomes these limitations b
10、y defining additional fields in a message header to describe new types of content and message structure. MIME defines the content-type header to specify the type and subtype of message content. For example, a message with an HTML attachment would have a content-type header set to text/html. SMTP and
11、 MIME are typically used together to send Internet e-mail messages.Figure2:Two types of protocols are used to retrieve messages from Internet mail servers: POP3 (Post Office Protocol 3) and IMAP4 (Internet Message Access Protocol 4). Although POP3 is more widely used than IMAP4, the latter has a num
12、ber of advantages. First, IMAP supports multiple folders on a remote mail server whereas POP3 supports only the Inbox folder. Second, IMAP supports message status flags (e.g., indicates whether a message has been previously seen); POP3 doesnt. These types of protocol features are important considera
13、tions in designing your application.JavaMail provides implementations of SMTP, IMAP4 and POP3. For more information on these Internet mail protocols, you can consult the pertinent RFCs.JavaMail ArchitectureNow that you have a basic understanding of Internet mail terms, we can begin to discuss the Ja
14、vaMail architecture. As shown in Figure 3, the architecture can be described in terms of three main layers. JavaMails layered architecture allows clients to use the JavaMail API with different message access protocols (POP3, IMAP4) and message transport protocols (SMTP).Figure3:The top layer is the
15、application layer that uses the JavaMail API. The second layer is the JavaMail API that defines a set of abstract classes and interfaces for supporting e-mail client functionality. This is the layer that frees a developer from having to deal with protocol-specific complexities. JavaMail provides con
16、crete subclasses of these abstract classes for Internet mail. The JavaMail API layer depends on concrete implementations of protocols.The implementation layer forms the third layer of the JavaMail architecture. Since JavaMail is protocol independent, its up to service providers to implement specific
17、 message access and message transfer protocols. Service provider implementations play a role similar to that of JDBC drivers. A provider registry allows service providers to register their protocol implementations to be used by JavaMail APIs. The JavaMail Web site has more information on third-party
18、 service providers.JavaBeans Activation FrameworkJavaMail interacts with message content through an intermediate layer called the JavaBeans Activation Framework (JAF), part of the Glasgow specification (a future release of the JavaBeans component model specification). In terms of dealing with e-mail
19、 messages, JAF provides a uniform way of determining the type of a messages content and encapsulating access to it. The JAF is implemented as a standard Java extension. Sun provides a royalty-free implementation of JAF that requires JDK 1.1.x or higher.JAF is used to get and set a messages text and
20、attachments. JavaMail provides convenient methods to interact with JAF. For example, MimeMessages setText() method can be used to set a string as a messages content with a MIME type of text/plain. Another example is MimeMessages getContent() method, which returns a messages content as a Java object
21、by invoking methods on JAFs DataHandler class.JAF can also be used to view e-mail attachments such as a text file (.txt) or an image (.gif) by instantiating a JavaBean that supports a particular command (e.g., view) on a specific type of message content. As shown below, the JAF DataSource object, wh
22、ich encapsulates the attachment, is used to create a DataHandler object. The DataHandler object uses a CommandInfo object to retrieve the pertinent JavaBean that can be used to perform a specific operation on an attachment. The JavaBean component can then be added to a frame, as shown in the code sn
23、ippet below. Currently, reference implementations of JAF-aware JavaBeans are available to view text, GIF and JPEG files. CommandInfo, DataSource and DataHandler are all JAF classes./ file name represents the attachmentFileDataSource attachFds = new FileDataSource(attachmentFilename);DataHandler dh =
24、 new DataHandler(attachFds);CommandInfo viewCi = dh.getCommand(view);Frame attachmentWindow = new Frame(View Attachment);/ add the bean to view the attachment to the main windowattachmentWindow.add(Component)dh.getBean(viewCi);Examples Using JavaMailYou now have a basic overview of the JavaMail arch
25、itecture and JAF so we can discuss the main JavaMail classes and methods needed to support an e-mail client. Table 1 describes some fundamental JavaMail classes.To illustrate the use of JavaMail in an e-mail client application, Ill consider four major use cases: configuring a connection to e-mail se
26、rvers, sending a message, getting messages from an e-mail server and deleting messages.Configuring a Connection to an e-Mail ServerBefore you can send or receive messages from your mail server, you need to establish a mail session between the mail client and the remote mail servers. Mail user proper
27、ties are used to initiate a connection to mail servers. The Session class can manage the mail user properties used by the JavaMail API./ Setting mail user propertiesmailProperties = new Properties();mailProperties.put(mail.transport.protocol, smtp);mailProperties.put(mail.smtp.host, someSmtpHost);Th
28、e Session object is a factory for Store and Transport objects. A Session and Store object can be obtained as follows:/ Get a Session objectSession session = Session.getDefaultInstance(mailProperties, null);/ Get a Store objectStore store = session.getStore();One issue to consider as you design the a
29、pplication architecture of your e-mail client is the dependency between your business layer and JavaMail. To reduce tight coupling between your applications business layer and the JavaMail subsystem, the Facade design pattern can be used. For example, mail user configuration can be passed into a Fac
30、ade (singleton) to assemble the appropriate JavaMail objects (Session, Transport and Store) and perform any other initialization (e.g., security). As a result, dependencies between your business layer classes and the JavaMail subsystem are reduced, and your business layer can use a simpler interface
31、 such as MailFacade.configure(Properties p).A use case pertaining to e-mail server connectivity is support for disconnected e-mail operation, which involves maintaining e-mail message stores on both the remote server and a local client, performing operations on both stores, and then being able to sy
32、nchronize these two stores. JavaSofts IMAP provider implements interfaces that can be used to support disconnected operation.At the time of this writing, secure messaging (e.g., support for S/MIME) is currently missing from JavaMail. S/MIME builds security on top of MIME to provide secure electronic
33、 messaging for Internet mail in the form of authentication and data security. Although not available in JavaMail, it can be obtained from a third party. The JavaMail Web site has more information on this and other third-party Web sites.Sending e-Mail MessagesOnce a mail session has been established,
34、 an e-mail message can be created and sent. First, a MimeMessage object needs to be constructed. Then, as shown below, the message object is initialized with the recipients e-mail address(es), the subject of the message and the message text. The message is then sent using the Transport object./ Crea
35、te new messageMessage msg = new MimeMessage(session);/ Initialize the messagemsg.setFrom(new InternetAddress(senderEmailAddress);msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipientEmail,false);msg.setSubject(subject);msg.setText(messageText);Transport.send(msg);JavaMail can al
36、so be used for developing mail-enabled servlets (e.g., using a browser to send e-mail to a support center). An important architectural consideration is reuse of the mail functionality in your business layer by both Web and Java clients. This can be accomplished by using a layered architecture and ap
37、propriate design patterns. For example, a simple mail Facade that shields a client from the JavaMail API can be used by both a Java client and a servlet to send an e-mail messge; a client needs to provide the view and controller components (Model-View-Controller design pattern) of the application.Wh
38、en sending messages, users assume that e-mail clients support address books, but JavaMail currently does not. However, the JavaMail API doesnt preclude you from developing your own mechanism (e.g., using XML - for implementing local address books or using JNDI to access an LDAP-enabled server for gl
39、obal address book features). Getting e-Mail MessagesAfter youve successfully established a mail session, an e-mail client can retrieve your e-mail messages. To retrieve your messages use the Session object to obtain a Store object, which can be used to obtain the Inbox folder, as shown below./ Openi
40、ng the Inbox Folderstore = session.getStore();store.connect();Folder folder = store.getFolder(INBOX);folder.open(Folder.READ_WRITE);After a folder has been successfully opened, its used to get message totals and the messages, as illustrated in the following code snippet./ Getting message totals and
41、messages from a folderint totalMessages = folder.getMessageCount();Message msgs = folder.getMessages();Note that the Message objects returned from the getMessages() method call are designed to be lightweight objects. For example, the Message objects returned could comprise only message header detail
42、s. Retrieval of the actual message content is deferred until the message content is actually used. Thus the getMessages() method isnt designed to be a resource-intensive operation.A typical e-mail client first displays a summary of messages in the form of header details such as sender (from), recipi
43、ents (to), subject and sent date. A summary line for each message can be obtained as follows.Address from = msgsi.getFrom();Address to = msgsi.getRecipients(Message.RecipientType.TO;String subject = msgsi.getSubject();Date d = msgsi.getSentDate();After viewing the message summary, a user typically d
44、ecides to view the actual message content in the form of text and/or attachments. Now were ready to get a messages content, which can be retrieved in the form of an object. The retrieved object depends on the type of content. If the content is a message with multiple attachments, a Multipart object
45、(a container of BodyPart objects) is returned. If the Parts content is text, then a simple String object is returned. To retrieve a messages content, you can invoke Parts getContent() method, as illustrated below. Note that Part is an interface implemented by Message and BodyPart classes.Object o =
46、part.getContent();If (o instanceof String) / content is text else if (o instanceof Multipart) / recursively iterate over containers contents to retrieve attachments else if (o instanceof Message) / message content could be a message itselfYouve now seen how messages are retrieved using JavaMail. If
47、your application supports both IMAP and POP, you may need to develop different algorithms to download messages, depending on your particular use case and performance requirements. For example, when developing applications for use with low bit-rate clients using POP (which doesnt maintain flags to in
48、dicate unread messages), downloading all messages each time becomes a performance issue. Thus you may need an algorithm that uses protocol-specific methods to prevent a redownload of messages. Depending on your requirements, other algorithms may be needed.Each of these different download algorithms
49、can be encapsulated as Strategy classes (Strategy design pattern) that share a common interface. A Strategy Factory can return strategy objects that can be used to download messages, depending on particular user configurations. This approach allows you to switch from one download algorithm to another, depending on
版权声明:以上文章中所选用的图片及文字来源于网络以及用户投稿,由于未联系到知识产权人或未发现有关知识产权的登记,如有知识产权人并不愿意我们使用,如有侵权请立即联系:2622162128@qq.com ,我们立即下架或删除。
Copyright© 2022-2024 www.wodocx.com ,All Rights Reserved |陕ICP备19002583号-1
陕公网安备 61072602000132号 违法和不良信息举报:0916-4228922