版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、javamail framework for developing internet-based e-mailclient applications原文:e-mail functionality is an important system requirement in areas suchi 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 you're 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 prov
3、ide e-mail features or using javasoffs javamail frameworkthis 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
4、designed to support cunent e-mail standards cind 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 addin
5、g 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, smt
6、p) 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 message's content is the actual message body and can comprise multiple parts in the form of text a
7、nd attachments, as shown in figurefigure 1: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 user's messages either permanently or until retrieved by an e-mail clie
8、nt.to develop 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 allo
9、wed only 7-bit ascii characters the mime (multipurpose internetmail 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 limit
10、ations by 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 ntext/htmlh.
11、 smtp and mime are typically used together to send internet e-mail messages.figure 2: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 1map4, the latter
12、 has a number of advantages first,imap supports multiple folders on a remote mail server whereas pop3 supports only the inbox folde匚 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 con
13、siderations 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 tenns. we can begin to discuss
14、the javamail architecture as shown in figure 3, the architecture can be described in terms of three main layers javamail's layered architecture allows clients to use the javamail api with different message access protocols (pop3, imap4) and message transport protocols (smtp)functionality. this i
15、s the layer that frees a developer from having to deal with protocol-specific complexities. javamail provides concrete subclasses of these abstract classes for internet mail. the javamail api layer depends on concrete implementations of protocolsthe implementation layer forms the third layer of the
16、javamail architecture since javamail is protocol independent, it's up to service providers to implement specific 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 t
17、heir protocol implementations to be used by javamail apis. the javamail web site has more information on third-party service providers javabeans activation frameworkjavamail interacts with message content through an intermediate layer called the javabeans activation framework (jaf), part of the glas
18、gow specification (a future release of the javabeans comp orient model specification). in terms of deali ng with e-mail messages, jaf provides a uniform way of determining the type of a message's content and encapsulating access to it. the jaf is implemented as a standard java extension. sun pro
19、vides a royalty-free implementation of jaf that requires jdk 1.1 .x or higher.jaf is used to get and set a message's text and attachments. javamail provides convenient methods to interact with jae for example, mimemessage settext() method can be used to set a string as a message's content wi
20、th a mime type of ntext/plain.h another example is mimemessage!s getcontent() method, which returns a message's content as a java object 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
21、javabean that supports a particular command (e.gm view) on a specific type of message content. as shown below, the jaf datasource object, which encapsulates the attachment, is used to create a datahandler object. the datahandler object uses a commandinfo object to retrieve the pertinent javabean tha
22、t 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 snippet below. currently, re fere nee implementations of jaf-aware javabeans are available to view text, gif and jpeg files commandinfo, datasource and datahandle
23、r are all jaf classes/ file name represents the attachmentfiledatasource attachfds = new filedatasource(attachmentfilename);datahandler dh = new datahandler(attachfds); commandinfo viewci = dh.getcommand(”view”); frame attachmentwindow = new frame(”view attachment11);/ add the bean to view the attac
24、hment to the main window attachmentwindow.add(componenl)dh.getbean(viewci);examples using javamailyou now have a basic overview of the javamail architecture and jaf so we can discuss the main javamail classes and methods needed to support an e-mail die nt. table 1 describes some fundamental javamail
25、 classes8 ess ionthu jivujniflclw represents a fralsewlon ind imes uthe miin entry pom for the jivimu api. the session oiss ccntfou loos to the store and trmspcrl o6)ecu.transport tms javumldus represents a trimpoit ient itat sends i musige io ts redptenb ushg i specific mesige tnnsfer protocol tn r
26、eport b lmp(<men>tf ty a setmce pwwerstoretms fivuinildus deftne a mojige jtore(> dilibue indin icceu protocef) for set of meuige mmeri folder oorcu are iccewed trough a store o*d stere b mptemefijed a sermce pcofmecfolder tms |ivumtdus canses cmuagss indsubldden in i treelke structure. i a
27、bo demes methods ( reweve decete . ueuige oo)scb ve icceued grouyi a fomer eject fower b tmpkmerted ” i service proirwermessage trts fivuunifldus modeu u> e-mu memi9e.ame»ige objed mends wth t$ content using jaf. theyu mail irter netmimemenge dais erftnos meuige to reroert i mime menage. mns
28、ige u knptemerttd ty a mmc« pxmdtraddress ths fivuraldus mode in e-mal iddrtis the itvixim utter net mem e(mdre4$ dus etfeflsmdrus to support memet e-cmi(mre»e$ cmtahandler mzqe cortentu represerted u ijivuactmtion otlihina- kr dus trial wns vo啲 the icfimi dm the oatahiatfer dus prwtdes in
29、 moeific« to the jaf.table 1:to illustrate the use of javtimail in an e-mail client application, fll consider four major use cases: configuring a connection to e-mail servers, sending a message, getting messages from an e-mail server and deleting messages.configuring a connection to an e-mail s
30、erverbefore 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 properties are used to initiate a connection to mail servers. the session class can manage the mail user properties used by the java
31、mail api./ setting mail user properties mailproperties = new properties(); mailproperties.put(umailtocor nsmtpm); mailproperties.put(hmail.smtp.host, msomesmtphostm);the session object is a factory for store and transport objects a session and store object can be obtained as follows:/ g
32、et a session objectsession session = session.getdefaultinstance(mailproperties, null);/ get a store objectstore store = session.getstore();one issue to consider as you design the application architecture of your e-mail client is the dependency between your business layer and javamail to reduce tight
33、 coupling between your application business layer and the javamail subsystem, the facade design pattern can be used. for example, mail user configuration can be passed into a facade (singleton) to assemble the appropriate javamail objects (session, transport and store) and perform any other initiali
34、zation (e.g., security). as a result, dependencies between your business layer classes and the javamailsubsystem are reduced, and your business layer can use a simpler interface such as mailfacade.configure(properties p).a use case pertaining to e-mail server connectivity is support for mdisconnecte
35、d e-mail operationwhich invoives maintaining e-mail message stores on both the remote server and a local client, performing operations on both stores, and then being able to synchronize these two stores. javasofvs imap provider implements interfaces that can be used to support disconnected operatio
36、n.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 messaging for internet mail in the form of authentication and data security although not available in javamail, it can be
37、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, an e-mail message can be created and sent. first, a mimemessage object needs to be constructed then, as shown below, the me
38、ssage 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./ create new messagemessage msg = new mimemessage(session);/ initialize the message msg.setfrom(new internetaddress(senderemailaddr
39、ess);msg.setrecipients(message.recipienttype.tojnternetaddress.parse(recipientemailfalse); msg.setsubject(subject); msg.settext(messagetext);transport.send(msg);javamail can also be used for developing mail-enabled servlets (e.g., using a browser to send e-mail to a support center). an important arc
40、hitectural consideration is reuse of the mail functionality in your business layer by both web and java dients. this can be accomplished by using a layered architecture and appropriate design patterns for example, a simple mail facade that shields a client from the javamail api can be used by both a
41、 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.when sending messages, users assume that e-mail dierhs support address books, but javamail curremly does not. however, the javam
42、ail api doesn't 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 global address book features). getting e-mail messagesafter you've successfully established a mail session, an e-mail clie
43、nt 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./ opening the inbox folderstore = session.getstore();store.connect();folder folder = store.getfolder(kinboxh);folder.open(fold
44、er.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 messages from a folderint totalmessages = folde匚getmessagecount();messagef msgs = folde匚getmessages();note that the m
45、essage objects returned from the getmessages() method call are designed to be lightweight objects. for example, the message objects returned could comprise only message header details retrieval of the actual message content is deferred until the message content is actually used. thus the getmessages
46、() method isn't designed to be a resource-intensive operationa typical e-mail client first displays a summary of messages in the form of header details such as sender (from), recipients (to), subject and sent date a summary line for each message can be obtained as follows.address! | from = msgsi
47、.getfrom();address to = msgsi|.getrecipients(message.recipienttype.to;string subject = itisgsil.getsubject();date d = msgsi .getsentdate();after viewing the message summary, a user typically decides to view the actual message content in the form of text and/or attachments now we're ready to get
48、a messaged 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 (a container of bodypart objects) is returned. if the part's content is text, then a simple string o
49、bject is returned. to retrieve a message's content, you can invoke part's getcontent() method, as illustrated below note that part is an interface implemented by message and bodypart classes.object o = part.getcontent();if (o instanceof string) / content is text else if (o instanceof multipa
50、rt) / recursively iterate over container's contents to retrieve attachments else if (o instanceof message) / message content could be a message itselfyou've now seen how messages are retrieved using javamail if your application supports both imap and pop, you may need to develop different al
51、gorithms 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 doesn't maintain flags to indicate unread messages), downloading all messages each time becomes a perfor
52、mance 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 neededeach of these different download algorithms can be encapsulated as strategy classes (strategy design pattern) that share a
53、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 the user configuration, and avoid having to use protocol-specifi
54、c conditional statements for more information on the strategy and other design patterns, consult design pattenisby gamma et al. (1995).when you download messages from a server, a feature thats available in some popular e-mail clients is an in box assistant to process incoming messages (e.gm delete m
55、essages based on user-specified rules) currently, javamail doesn't provide direct support for features such as automated message filteringdeleting e-mail messagesa standard use case for e-mail clients is deleting a message. using javamail, deleting messages from a folder is a simple two-step pro
56、cess. first, messages are marked for deletion. those messages that have been marked are then deleted from a folder by either explicitly invoking a folder's expunge() method or closing a folder with the expunge parameter of the close() method set to true./ set delete message flagmessage.setflag(f
57、lags.flag.deleted, true);/ delete marked messages from folder folder.close(true);conclusionthis short introduction should help you use javamail 1.1 to develop an e-mail client application. javamail is a relatively new framework that will inevitably continue to mature and evolve nevertheless, it can
58、be used to rapidly develop an e-mail client application using a higher-level api without having to perform the arduous task of implementing specific mail protocols and developing an architectural infrastructure to support multiple protocols. you can obtain more information on javamail/jaf, including
59、 sample programs for sending and retrieving e-mail messages, from the references listed below.resourcesjavamail: wwwiavasoftcom/droducts(iavamail/index.htmljavabeans activation framework: gamma, e., helm, r., johnson, r., and vlissides, j. (1995).design patterns: elements of reusable object-oriented software author bioian moraes, phd,is a
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
评论
0/150
提交评论