1、Fundamentals of the JavaMail APIPresented 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 tips 22. Introducing the JavaMail API 33. Reviewing related protocols 44. Installin
2、g JavaMail 65. Reviewing the core classes 86. Using the JavaMail API 137. Searching with SearchTerm 218. Exercises 229. Wrapup 32Fundamentals of the JavaMail API Page 1Section 1. Tutorial tipsShould I take this tutorial?Looking to incorporate mail facilities into your platform-independent Java solut
3、ions? Look nofurther than the JavaMail API, which offers a protocol-independent model for working withIMAP, POP, SMTP, MIME, and all those other Internet-related messaging protocols. Withthe help of the JavaBeans Activation Framework (JAF), your applications can now bemail-enabled through the JavaMa
4、il API.ConceptsAfter completing this module you will understand the:* Basics of the Internet mail protocols SMTP, POP3, IMAP, and MIME* Architecture of the JavaMail framework* Connections between the JavaMail API and the JavaBeans Activation FrameworkObjectivesBy the end of this module you will be a
5、ble 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 messagesPrerequisitesInstructions on how to download and install the JavaMail API are contained in the course. Inaddition, you will need a developm
6、ent environment such as the JDK 1.1.6+ or the Java 2Platform, Standard Edition (J2SE) 1.2.x or 1.3.x.A general familiarity with object-oriented programming concepts and the Java programminglanguage is necessary. The Java language essentials tutorial can help.copyright 1996-2000 Magelang Institute db
7、a jGuruContactjGuru has been dedicated to promoting the growth of the Java technology communitythrough evangelism, education, and software since 1995. You can find out more abouttheir activities, including their huge collection of FAQs at jG . To send feedbackto jGuru about this course, send mail to
8、 .Course author: Formerly with jG , John Zukowski does strategic Javaconsulting for JZ Ventures, Inc. His latest book is titled Java Collections from Apress .Presented by developerWorks, your source for great tutorials of the JavaMail API Page 2Section 2. Introducing the JavaMail APIWhat is the Ja
9、vaMail API?The JavaMail API is an optional package (standard extension) for reading, composing, andsending electronic messages. You use the package to create Mail User Agent (MUA) typeprograms, similar to Eudora, pine, and Microsoft Outlook. The APIs main purpose is not fortransporting, delivering,
10、and forwarding messages; this is the purview of applications such assendmail and other Mail Transfer Agent (MTA) type programs. MUA-type programs let usersread and write e-mail, whereas MUAs rely on MTAs to handle the actual delivery.The JavaMail API is designed to provide protocol-independent acces
11、s for sending andreceiving messages by dividing the API into two parts:* The first part of the API is the focus of this course - basically, how to send and receivemessages independent of the provider/protocol.* The second part speaks the protocol-specific languages, like SMTP, POP, IMAP, andNNTP. Wi
12、th the JavaMail API, in order to communicate with a server, you need aprovider for a protocol. The creation of protocol-specific providers is not covered in thiscourse because Sun provides a sufficient set for free.Presented by developerWorks, your source for great tutorials of the JavaMail API Pag
13、e 3Section 3. Reviewing related protocolsIntroductionBefore looking into the 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. Under
14、standing the basics of all theprotocols will help you understand how to use the JavaMail API. While the API is designed tobe protocol agnostic, you cant overcome the limitations of the underlying protocols. If acapability isnt supported by a chosen protocol, the JavaMail API doesnt magically add the
15、capability on top of it. (As youll soon see, this can be a problem when working with 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-based program willcommunicate with your com
16、pany or Internet Service Providers (ISPs) SMTP server. ThatSMTP server will relay the message on 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 authentication is supported, but it is yo
17、ur responsibility to ensure theSMTP server is configured properly. There is nothing in the JavaMail API for tasks likeconfiguring a server to relay messages or to add and remove e-mail accounts.POPPOP stands for Post Office Protocol. Currently in version 3, also known as POP3, RFC 1939defines this p
18、rotocol. POP is the mechanism most people on the Internet use to get theirmail. It defines support 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
19、 messages they have, are not supported by POP at all.These capabilities are built into programs like 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
20、 calculate it yourself.IMAPIMAP is a more advanced protocol for receiving messages. Defined in RFC 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
21、to use IMAP instead of POP and expect everything in IMAP to be supported.Assuming your mail server supports IMAP, your JavaMail-based program can takePresented by developerWorks, your source for great tutorials of the JavaMail API Page 4advantage of users having multiple folders on the server and t
22、hese 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 m
23、ultiple foldersfor each user. While this does centralize backups, as users long-term mail folders get largerand larger, everyone suffers when disk space is exhausted. With POP, saved messages getoffloaded from the mail server.MIMEMIME stands for Multipurpose Internet Mail Extensions. It is not a mai
24、l transfer 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 th
25、ese formats. 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 maintains a list of third-party providers thattake advantage of protocols fo
26、r which Sun does not provide out-of-the-box support. Youllfind support for NNTP (Network News Transport Protocol) newsgroups, S/MIME (SecureMultipurpose Internet Mail Extensions), and more.Presented by developerWorks, your source for great tutorials of the JavaMail API Page 5Section 4. Installing J
27、avaMailIntroductionThere are two versions of the JavaMail API commonly used 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 version of the Java 2 Platform, Enterprise Edition (J2EE), so it is stillcommonly
28、 used. 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 Suns JavaMail implementation, you can find many example programsin the demo
29、 directory.Installing JavaMail 1.2To use the JavaMail 1.2 API, download the JavaMail 1.2 implementation, unbundle thejavamail-1_2.zip file, and add the mail.jar file to your CLASSPATH. The 1.2implementation comes with an SMTP, IMAP4, and POP3 provider besides the core classes.After installing JavaMa
30、il 1.2, install the JavaBeans Activation Framework.Installing JavaMail 1.1.3To use the JavaMail 1.1.3 API, download the JavaMail 1.1.3 implementation, unbundle thejavamail1_1_3.zip file, and add the mail.jar file to your CLASSPATH. The 1.1.3implementation comes with an SMTP and IMAP4 provider, besid
31、es 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. Afterdownloading and unbundling pop31_1_1.zip, add pop3.jar to your CLASSPATH, too.After installing JavaMail 1.1.3, instal
32、l the JavaBeans Activation Framework.Installing the JavaBeans Activation FrameworkAll versions of the JavaMail API require the JavaBeans Activation Framework. Theframework adds support for typing arbitrary blocks of data and handling it accordingly. Thisdoesnt sound like much, but it is your basic M
33、IME-type support found in many browsers andmail tools today. After downloading the framework, unbundle the jaf1_0_1.zip file, andadd the activation.jar file to your CLASSPATH.For JavaMail 1.2 users, you should now have added mail.jar and activation.jar toyour CLASSPATH.For JavaMail 1.1.3 users, you
34、should now have added mail.jar, pop3.jar, andactivation.jar to your CLASSPATH. If you have no plans of using POP3, you dontPresented by developerWorks, your source for great tutorials of the JavaMail API Page 6need to add pop3.jar to your CLASSPATH.If you dont want to change the CLASSPATH environme
35、nt variable, copy the jar files to yourlib/ext directory under the Java Runtime Environment (JRE) directory. For instance, forthe J2SE 1.3 release, the default directory would be C:jdk1.3jrelibext on aWindows platform.Using JavaMail with the Java 2 Enterprise EditionIf you use J2EE, there is nothing
36、 special you have to do to use the basic JavaMail API; itcomes with the J2EE classes. Just make sure the j2ee.jar file is in your CLASSPATH andyoure all set.For J2EE 1.2.1, the POP3 provider comes separately, so download and follow the steps toinclude the POP3 provider as shown in the previous secti
37、on “Installing JavaMail 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 JavaBeans Activation Framework.ExerciseExercise 1. How to set up a JavaMail environment on page 22Presented by developerWorks, yo
38、ur source for great tutorials of the JavaMail API Page 7Section 5. Reviewing the core classesIntroductionBefore taking a how-to approach at looking at the JavaMail classes in depth, this sectionwalks you through the core classes that make up the API: Session, Message, Address,Authenticator, Transpo
39、rt, Store, and Folder. All these classes are found in thetop-level package for the JavaMail API, javax.mail, though youll frequently find yourselfusing subclasses found in the javax.mail.internet package.SessionThe Session class defines a basic mail session. It is through this session that everythin
40、gelse works. The Session object takes advantage of a java.util.Properties object toget information like mail server, username, password, and other information that can beshared across your entire application.The constructors for the class are private. You can get a single default session that can be
41、shared with the getDefaultInstance() method:Properties props = new Properties();/ fill props with any informationSession session = Session.getDefaultInstance(props, null);Or, you can create a unique session with getInstance():Properties props = new Properties();/ fill props with any informationSessi
42、on session = Session.getDefaultInstance(props, null);In both cases, the null argument is an Authenticator object that is not being used at thistime.In most cases, it is sufficient to use the shared session, even if working with mail sessions formultiple user mailboxes. You can add the username and p
43、assword combination in at a laterstep in the communication process, keeping everything separate.MessageOnce you have your Session object, it is time to move on to creating the message to send.This is done with a type of Message . Because Message is an abstract class, you mustwork with a subclass, in
44、 most cases javax.mail.internet.MimeMessage . AMimeMessage is an e-mail message that understands MIME types and headers, as definedin the different RFCs. Message headers are restricted to US-ASCII characters only, thoughnon-ASCII characters can be encoded in certain header fields.To create a Message
45、, pass along the Session object to the MimeMessage constructor:MimeMessage message = new MimeMessage(session);Presented by developerWorks, your source for great tutorials of the JavaMail API Page 8Note: There are other constructors, like for creating messages from RFC822-formatted inputstreams.Once
46、 you have your message, you can set its parts, as Message implements the Partinterface (with MimeMessage implementing MimePart ). The basic mechanism to set thecontent is the setContent() method, with arguments for the content and the mime type:message.setContent(“Hello“, “text/plain“);If, however,
47、you know you are working with a MimeMessage and your 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 mechanism to set the conten
48、t. Forsending other kinds of messages, like HTML messages, use the former.For setting the subject, use the setSubject() method:message.setSubject(“First“);AddressOnce youve created the Session and the Message, as well as filled the message withcontent, it is time to address your letter with an Address . Like Message, Address is anabstract class. You use the javax.mail.internet.InternetAddress class.To create an address with just the e-mail address, pass the e-mail address to theconstructor:Address address = new InternetAddress(“presidentwhitehouse.gov“);If