2022年JavaMail开发手册 .pdf

上传人:C****o 文档编号:32190692 上传时间:2022-08-08 格式:PDF 页数:33 大小:326.51KB
返回 下载 相关 举报
2022年JavaMail开发手册 .pdf_第1页
第1页 / 共33页
2022年JavaMail开发手册 .pdf_第2页
第2页 / 共33页
点击查看更多>>
资源描述

《2022年JavaMail开发手册 .pdf》由会员分享,可在线阅读,更多相关《2022年JavaMail开发手册 .pdf(33页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、Fundamentalsof the JavaMailAPIPresented by developerWorks,your source for great of ContentsIf youre viewing this document online, you can click any of the topics below to link directly to that section.1. Tutorial tips22. Introducing the JavaMail API33. Reviewing related protocols44. Installing JavaM

2、ail65. Reviewing the core classes86. Using the JavaMail API137. Searching with SearchTerm218. Exercises229. Wrapup32Fundamentals of the JavaMail APIPage 1名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 1 页,共 33 页 - - - - - - - - - Section 1. Tutorial tipsShould I take

3、 this tutorial?Looking to incorporatemail facilities into your platform-independentJava solutions?Look nofurther than the JavaMail API, which offers a protocol-independentmodel for working withIMAP, POP, SMTP, MIME, and all those other Internet-relatedmessaging protocols. Withthe help of the JavaBea

4、nsActivation Framework(JAF), your applications can now bemail-enabledthrough the JavaMail API.ConceptsAfter completingthis module you will understandthe:*Basics of the Internet mail protocols SMTP, POP3, IMAP, and MIME*Architectureof the JavaMail framework*Connectionsbetween the JavaMail API and the

5、 JavaBeansActivation FrameworkObjectivesBy the end of this module you will be able to:*Send and read mail using the JavaMail API*Deal with sending and receiving attachments*Work with HTML messages*Use search terms to search for messagesPrerequisitesInstructionson how to download and install the Java

6、MailAPI are contained in the course. Inaddition, you will need a developmentenvironmentsuch as the JDK 1.1.6+ or the Java 2Platform, StandardEdition (J2SE) 1.2.x or 1.3.x.A general familiarity with object-orientedprogrammingconcepts and the Java programminglanguage is necessary. The Java language es

7、sentialstutorial can help.copyright 1996-2000Magelang Institute dba jGuruContactjGuru has been dedicated to promoting the growth of the Java technologycommunitythrough evangelism,education,and software since 1995. You can find out more abouttheir activities, including their huge collection of FAQs a

8、t jG. To send feedbackto jGuru about this course, send mail to .Courseauthor:Formerly with jG, John Zukowskidoes strategic Javaconsultingfor JZ Ventures,Inc. His latest book is titled Java Collections from Apress .Presented by developerWorks,your source for great of the JavaMail APIPage 2名师资料总结 - -

9、-精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 2 页,共 33 页 - - - - - - - - - Section 2. Introducing the JavaMail APIWhat is the JavaMail API?The JavaMail API is an optional package (standardextension) for reading, composing,andsending electronic messages.You use the package to c

10、reate Mail User Agent (MUA) typeprograms,similar to Eudora, pine, and Microsoft Outlook. The APIs main purpose is not fortransporting,delivering,and forwardingmessages; this is the purview of applicationssuch assendmail and other Mail Transfer Agent (MTA) type programs.MUA-typeprograms let usersread

11、 and write e-mail,whereas MUAs rely on MTAs to handle the actual delivery.The JavaMail API is designed to provide protocol-independentaccess for sending andreceiving messagesby dividing the API into two parts:*The first part of the API is the focus of this course -basically, how to send and receivem

12、essagesindependentof the provider/protocol.*The second part speaks the protocol-specificlanguages, like SMTP, POP, IMAP, andNNTP. With the JavaMail API, in order to communicatewith a server, you need aprovider for a protocol. The creation of protocol-specificproviders is not covered in thiscourse be

13、cause Sun provides a sufficient set for free.Presented by developerWorks,your source for great of the JavaMail APIPage 3名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 3 页,共 33 页 - - - - - - - - - Section 3. Reviewing related protocolsIntroductionBefore looking into t

14、he JavaMail API specifics, lets step back and take a look at the protocolsused with the API. There are basically four that youll come to know and love:*SMTP*POP*IMAP*MIMEYou will also run across NNTP and some others. Understandingthe basics of all theprotocols will help you understandhow to use the

15、JavaMail API. While the API is designed tobe protocol agnostic,you cant overcome the limitationsof the underlyingprotocols. If acapability isnt supportedby a chosen protocol, the JavaMail API doesnt magically add thecapability on top of it. (As youll soon see, this can be a problem when working with

16、 POP.)SMTPThe Simple Mail Transfer Protocol (SMTP) is defined by RFC 821 . It defines the mechanismfor delivery of e-mail.In the context of the JavaMail API, your JavaMail-basedprogram willcommunicatewith your company or Internet Service Providers (ISPs) SMTP server. ThatSMTP server will relay the m

17、essageon to the SMTP server of the recipient(s)to eventuallybe acquired by the user(s) through POP or IMAP. This does not require your SMTP server tobe an open relay, as authenticationis supported, but it is your responsibilityto ensure theSMTP server is configuredproperly. There is nothing in the J

18、avaMail API for tasks likeconfiguring a server to relay messagesor to add and remove e-mailaccounts.POPPOP stands for Post Office Protocol. Currently in version 3, also known as POP3, RFC 1939defines this protocol. POP is the mechanismmost people on the Internet use to get theirmail. It defines supp

19、ort for a single mailbox for each user. That is all it does, and that is alsothe source of a lot of confusion.Much of what people are familiar with when using POP, likethe ability to see how many new mail messagesthey have, are not supported by POP at all.These capabilitiesare built into programs li

20、ke Eudora or Microsoft Outlook, which rememberthings like the last mail received and calculate how many are new for you. So, when usingthe JavaMail API, if you want this type of information,you have to calculate it yourself.IMAPIMAP is a more advanced protocol for receiving messages. Defined in RFC

21、2060 , IMAPstands for Internet Message Access Protocol, and is currently in version 4, also known asIMAP4. When using IMAP, your mail server must support the protocol. You cant just changeyour program to use IMAP instead of POP and expect everythingin IMAP to be supported.Assuming your mail server s

22、upports IMAP, your JavaMail-basedprogram can takePresented by developerWorks,your source for great of the JavaMail APIPage 4名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 4 页,共 33 页 - - - - - - - - - advantage of users having multiple folders on the server and these

23、folders can be shared bymultiple users.Due to the more advanced capabilities,you might think IMAP would be used by everyone. Itisnt. It places a much heavier burden on the mail server, requiring the server to receive thenew messages, deliver them to users when requested, and maintain them in multipl

24、e foldersfor each user. While this does centralize backups, as users long-termmail folders get largerand larger, everyonesuffers when disk space is exhausted. With POP, saved messages getoffloaded from the mail server.MIMEMIME stands for MultipurposeInternet Mail Extensions.It is not a mail transfer

25、 protocol.Instead, it defines the content of what is transferred:the format of the messages,attachments,and so on. There are many different documents that take effect here: RFC 822, RFC 2045 , RFC 2046 , and RFC 2047 . As a user of the JavaMail API, you usually dontneed to worry about these formats.

26、 However,these formats do exist and are used by yourprograms.NNTP and othersBecause of the split of the JavaMail API between provider and everything else, you caneasily add support for additional protocols. Sun maintainsa list of third-partyproviders thattake advantage of protocols for which Sun doe

27、s not provide out-of-the-boxsupport. Youllfind support for NNTP (Network News Transport Protocol) newsgroups,S/MIME (SecureMultipurposeInternet Mail Extensions),and more.Presented by developerWorks,your source for great of the JavaMail APIPage 5名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - -

28、- 名师精心整理 - - - - - - - 第 5 页,共 33 页 - - - - - - - - - Section 4. Installing JavaMailIntroductionThere are two versions of the JavaMail API commonlyused today: 1.2 and 1.1.3. All theexamples in this course will work with both. While 1.2 is the latest, 1.1.3 is the versionincluded with the 1.2.1 versi

29、on of the Java 2 Platform, EnterpriseEdition (J2EE), so it is stillcommonlyused. The version of the JavaMail API you want to use affects what you downloadand install. All will work with JDK 1.1.6+, Java 2 Platform, Standard Edition (J2SE) version1.2.x, and J2SE version 1.3.x.Note: After installing S

30、uns JavaMail implementation,you can find many example programsin the demo directory.Installing JavaMail 1.2To use the JavaMail 1.2 API, download the JavaMail 1.2 implementation,unbundlethejavamail-1_2.zipfile, and add the mail.jarfile to your CLASSPATH.The 1.2implementationcomes with an SMTP, IMAP4,

31、 and POP3 provider besides the core classes.After installing JavaMail 1.2, install the JavaBeansActivation Framework.Installing JavaMail 1.1.3To use the JavaMail 1.1.3 API, download the JavaMail 1.1.3 implementation,unbundle thejavamail1_1_3.zipfile, and add the mail.jarfile to your CLASSPATH.The 1.

32、1.3implementationcomes with an SMTP and IMAP4 provider, besides the core classes.If you want to access a POP server with JavaMail 1.1.3, download and install a POP3provider. Sun has one available separate from the JavaMail implementation.Afterdownloadingand unbundling pop31_1_1.zip, add pop3.jarto y

33、our CLASSPATH,too.After installing JavaMail 1.1.3, install the JavaBeansActivation Framework.Installing the JavaBeans Activation FrameworkAll versions of the JavaMail API require the JavaBeansActivation Framework.Theframework adds support for typing arbitrary blocks of data and handling it according

34、ly.Thisdoesnt sound like much, but it is your basic MIME-typesupport found in many browsersandmail tools today. After downloadingthe framework,unbundle the jaf1_0_1.zipfile, andadd the activation.jarfile to your CLASSPATH.For JavaMail 1.2 users, you should now have added mail.jarand activation.jarto

35、your CLASSPATH.For JavaMail 1.1.3 users, you should now have added mail.jar, pop3.jar, andactivation.jarto your CLASSPATH.If you have no plans of using POP3, you dontPresented by developerWorks,your source for great of the JavaMail APIPage 6名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师

36、精心整理 - - - - - - - 第 6 页,共 33 页 - - - - - - - - - need to add pop3.jarto your CLASSPATH.If you dont want to change the CLASSPATHenvironmentvariable, copy the jar files to yourlib/extdirectory under the Java Runtime Environment(JRE) directory. For instance,forthe J2SE 1.3 release, the default directo

37、ry would be C:jdk1.3jrelibexton aWindows platform.Using JavaMail with the Java 2 Enterprise EditionIf you use J2EE, there is nothing special you have to do to use the basic JavaMail API; itcomes with the J2EE classes. Just make sure the j2ee.jarfile is in your CLASSPATHandyoure all set.For J2EE 1.2.

38、1, the POP3 provider comes separately, so download and follow the steps toinclude the POP3 provider as shown in the previous section InstallingJavaMail 1.1.3. J2EE1.3 users get the POP3 provider with J2EE so do not require the separate installation.Neither installation requires you to install the Ja

39、vaBeansActivation Framework.ExerciseExercise 1. How to set up a JavaMail environmenton page 22Presented by developerWorks,your source for great of the JavaMail APIPage 7名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 7 页,共 33 页 - - - - - - - - - Section 5. Reviewing t

40、he core classesIntroductionBefore taking a how-toapproach at looking at the JavaMail classes in depth, this sectionwalks you through the core classes that make up the API: Session, Message , Address,Authenticator, Transport, Store, and Folder. All these classes are found in thetop-levelpackage for t

41、he JavaMail API, javax.mail, though youll frequently find yourselfusing subclassesfound in the javax.mail.internetpackage.SessionThe Sessionclass defines a basic mail session. It is through this session that everythingelse works. The Sessionobject takes advantageof a java.util.Propertiesobject toget

42、 informationlike mail server, username, password,and other informationthat can beshared across your entire application.The constructorsfor the class are private. You can get a single default session that can beshared with the getDefaultInstance()method:Propertiesprops= new Properties();/fillpropswit

43、hanyinformationSessionsession= Session.getDefaultInstance(props,null);Or, you can create a unique session with getInstance():Propertiesprops= new Properties();/fillpropswithanyinformationSessionsession= Session.getDefaultInstance(props,null);In both cases, the nullargument is an Authenticatorobject

44、that is not being used at thistime.In most cases, it is sufficientto use the shared session, even if working with mail sessions formultiple user mailboxes. You can add the usernameand password combinationin at a laterstep in the communicationprocess, keeping everythingseparate.MessageOnce you have y

45、our Sessionobject, it is time to move on to creating the message to send.This is done with a type of Message. Because Messageis an abstract class, you mustwork with a subclass, in most cases javax.mail.internet.MimeMessage. AMimeMessageis an e-mailmessage that understandsMIME types and headers, as d

46、efinedin the different RFCs. Message headers are restricted to US-ASCIIcharactersonly, thoughnon-ASCIIcharacters can be encoded in certain header fields.To create a Message , pass along the Sessionobject to the MimeMessageconstructor:MimeMessagemessage= new MimeMessage(session);Presented by develope

47、rWorks,your source for great of the JavaMail APIPage 8名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 8 页,共 33 页 - - - - - - - - - Note: There are other constructors,like for creating messages from RFC822-formattedinputstreams.Once you have your message, you can set i

48、ts parts, as Messageimplementsthe Partinterface (with MimeMessageimplementingMimePart). The basic mechanismto set thecontent is the setContent()method, with argumentsfor the content and the mime type:message.setContent(Hello,text/plain);If, however, you know you are working with a MimeMessageand you

49、r message is plain text,you can use its setText()method, which only requires the actual content, defaulting to theMIME type of text/plain:message.setText(Hello);For plain text messages,the latter form is the preferred mechanismto set the content. Forsending other kinds of messages, like HTML message

50、s, use the former.For setting the subject, use the setSubject()method:message.setSubject(First);AddressOnce youve created the Sessionand the Message , as well as filled the message withcontent, it is time to address your letter with an Address. Like Message , Addressis anabstract class. You use the

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 高考资料

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁