Java API Interpretation

Source: Internet
Author: User

The JavaMail API is an optional package that reads, writes, and sends electronic information. We can use it to build mail user agents such as Eudora, Foxmail, MS Outlook Express (mail users agent, abbreviated as MUA). Let's see how the JavaMail API provides access to information! The JavaMail API is designed to send and receive electronic messages in a way that does not rely on protocols, and focuses on how to send and receive electronic messages in a way that does not rely on protocols, as described in this article.


Copyright NOTICE: This article is free to reprint, please be sure to use hyperlinks in the form of the original source of the article and the author's information and this statement

Author: cleverpig (author of Blog:http://blog.matrix.org.cn/page/cleverpig)

Original: http://www.matrix.org.cn/resource/article/44/44101_JavaMail.html

Keyword: java,mail,pop,smtp


I. Introduction of JavaMail API

The JavaMail API is an optional package that reads, writes, and sends electronic information. We can use it to build mail user agents such as Eudora, Foxmail, MS Outlook Express (mail users agent, abbreviated as MUA). Instead of sending, delivering, and forwarding messages like SendMail or other mail transfer agents (mail Transfer agent, MTA) programs. From another point of view, these e-mail users use MUA programs to read and write messages daily, while MUA relies on the MTA to process mail deliveries.

Now that we know the relationship between MUA and MTA, let's look at how the JavaMail API provides access to information. The JavaMail API is designed to send and receive electronic information in a way that is not protocol-dependent, and this API is divided into two parts:


Basic features: How to send and receive electronic messages in a way that is not dependent on the protocol, as described in this article, but in the following paragraphs you will see that this is just wishful thinking.

The second part is dependent on a specific protocol, such as SMTP, POP, IMAP, and NNTP protocol. In this part of the JavaMail API is to communicate with the server, not in the contents of this article.


Ii. List of related agreements

Before we step into the JavaMail API, let's look at the protocols involved in the API. Here are 4 great information transfer protocols that everyone knows and is happy to use:

Smtp

POP

Imap

Mime

Of course, the above 4 protocols, not all, there are NNTP and some other protocols can be used to transfer information, but because it is not commonly used, so this article does not mention. Understanding these 4 basic protocols helps us to better use the JavaMail API. However, the JavaMail API is designed to be protocol agnostic, and we are not able to overcome the constraints of these protocols at this time. To be exact, if the features we use are not supported by the protocols we choose, then the JavaMail API is unlikely to magically empower us like magicians.


1. Smtp

The Simple Mail Transfer Protocol defines the mechanism for delivering mail. Below, we will use the Java-mail-based program to communicate with the company or the ISP's SMTP server. The SMTP server forwards the message to the recipient's SMTP server until it is finally acquired by the recipient via a POP or IMAP protocol. This does not require the SMTP server to use mail forwarding that supports authorization, but it does pay attention to the correct setting of the SMTP server (SMTP server settings are not related to the JavaMail API).


2. POP

Pop is a post Office protocol, currently a 3rd version, known as POP3. Pop defines a mechanism for how a user obtains a message. It specifies that each user uses a separate mailbox. Most of the features that most people are familiar with when using pop are not supported, such as viewing the number of new messages in a mailbox. And this feature is built in Microsoft Outlook, then it means that Microsoft Outlook and other mail client software by querying the most recently received messages to calculate the number of new messages to achieve the previously mentioned functionality. So when we use the JavaMail API we need to be aware that we have to do our own calculations when we need to get information like the number of new messages we talked about earlier.


3. Imap

IMAP uses a high-level protocol for receiving information, and the current version is the 4th edition, so it is also known as IMAP4. It is important to note that the mail server must support this protocol when using IMAP. In this respect, we can't use IMAP as a substitute for pop, and we can't expect IMAP to be supported anywhere. If the mail server supports IMAP, then our mail program will be able to have the following features that are supported by IMAP: Each user can have multiple directories on the server, which can be shared among multiple users.

It's obviously more advanced than pop, but when trying to take IMAP, we realize that it's not perfect: because IMAP needs to receive new information from other servers, deliver that information to users, and maintain multiple directories for each user, which brings a high load on the mail server. And one of the differences between IMAP and POP is that pop users download messages from the mail server when they receive mail, and IMAP allows users to access the mail directory directly, so when the mail server makes a backup job, the mail directory for each user who uses this messaging system for a long time occupies a lot of space. This will directly cause a spike in disk space on the mail server.


4. Mime

MIME is not the protocol used to deliver messages, it defines the format of message content as an extension of a multipurpose message: Information format, attachment format, and so on. Some RFC standards involve MIME:RFC 822, RFC 2045, RFC 2046, RFC 2047, and interested matrixer can read about it. As developers of the JavaMail API, we don't have to care about these format definitions, but these formats are used in programs.


5. NNTP and other third-party protocols

Because the JavaMail API is designed with the separation of the third-party protocol implementation providers in mind, we can easily add some third-party protocols. Sun maintains a list of third-party protocol implementation providers: Http://java.sun.com/products/javamail/Third_ Party.html, through this list we can find the required third-party protocols that are not supported by Sun: such as NNTP, the newsgroup protocol and S/MIME, this secure MIME protocol.


Third, installation

1. Installing JavaMail

In order to use the JavaMail API, you need to download the file name format Javamail-[version] from http://java.sun.com/products/javamail/downloads/index.html. ZIP file (This file includes the JavaMail implementation) and add the Mail.jar file to the classpath. This implementation provides support for SMTP, IMAP4, POP3.

Note: After installing the JavaMail implementation, we will find many interesting simple instance programs in the demo directory.

After installing the JavaMail, we also need to install the JavaBeans Activation Framework, as this framework is required by the JavaMail API. If we use the Java EE, then we do not need to download javamail separately, because it exists in J2ee.jar, just add J2ee.jar to classpath.


2. Installing the JavaBeans Activation Framework

Download the JavaBeans Activation Framework from http://java.sun.com/products/javabeans/glasgow/jaf.html and add it to classpath. This framework adds to the classification of any block of data, as well as the characteristics of processing them. These features are required by the JavaMail API. While this sounds very vague, it only provides basic MIME type support for our JavaMail API.

So far, we should add both Mail.jar and Activation.jar to the classpath.

Of course, it is also possible to copy the two jar files directly into the Lib/ext directory of the JRE directory from a convenient point of view.


Iv. initial knowledge of the JavaMail API

1. Learn about our JavaMail environment

A Overview JavaMail Core class Structure

Opening the Javamail.jar file, we will find that there are some core classes under Javax.mail's package: Session, Message, Address, Authenticator, Transport, Store, Folder. And there are some common subclasses in the Javax.mail.internet package.

B Session

The session class defines a basic mail session. Just like an HTTP session, our job of sending and receiving mail is based on this session. The session object takes advantage of the Java.util.Properties object to obtain the mail server, user name, password information, and the shared information that the entire application uses.

The constructor of the session class is private, so we can get a default session object using the static factory method provided by the session class Getdefaultinstance ():


Properties Props = new properties ();

Fill props with any information

Session session = Session.getdefaultinstance (props, null);


Or use the static Factory method getinstance () to get a custom session:


Properties Props = new properties ();

Fill props with any information

Session session = Session.getinstance (props, null);


From the two examples above, it is not difficult to see that the second parameter of the Getdefaultinstance () and getinstance () methods are null, because in the above example, there is no use of the mail authorization, the authorization is described in detail later in this article.

From many instances, it is sufficient to use a shared session during access to the mail server, even when working in multiple user mailbox modes.


C Message

When we set up the session object, we can send the structure of the message body. Here Sun provides a message type to help developers do the job. Because message is an abstract class, in most cases we use the subclass Javax.mail.internet.MimeMessage, which is the mailbox information that uses MIME types, MIME information headers. The information header can use only us-ascii characters, and non-ASCII characters are converted to ASCII by encoding.

In order to create a MimeMessage object, we must pass the session object as a parameter of the MimeMessage constructor method:


MimeMessage message = new MimeMessage (session);


Note: There are a number of construction methods for the MimeMessage class, such as using an input stream as the constructor for the parameter.


After setting up the MimeMessage object, we need to set up its parts, and for the MimeMessage class, the part is the MimePart interface. The most basic way to set information content is to call the SetContent () method by means of a parameter that represents the content of the message and the type of meter:


Message.setcontent ("Hello", "Text/plain");


However, if the information in the mimemessage we use is text, we can directly use the SetText () method to conveniently set the text content.


Message.settext ("Hello");


The two methods mentioned earlier, for text information, the latter is more appropriate. For some other types of information, such as HTML information, use the former.

Don't forget, use the Setsubject () method to set the message subject for the message:


Message.setsubject ("first");


D Address

Here we have set up the session and message, and we'll show you how to use the email address class: address. Like a message, the address class is also an abstract class, so we will use the Javax.mail.internet.InternetAddress subclass.

By passing in a string representing the e-mail address, we can create a mail address class:


Address address = new InternetAddress ("[email protected]");


If you want to add a name after the email address, you can create a mail address class with a mail address and a name by passing two parameters: a string representing the e-mail address and the first name:


Address address = new InternetAddress ("[Email protected]", "George Bush");


In this article, the e-mail address class is intended to set the sender and recipient of the mail message, and after the e-mail address class has been established, we set the sender of the message via message Setfrom () and Setreplyto ():


Message.setfrom (address);

Message.setreplyto (address);


If there is more than one sender address in the email, we can add the sender by AddForm () method:


Address address[] = ...;

Message.addfrom (address);


In order to set up the recipient, we use the AddRecipient () method to increase the recipient, which requires the use of Message.recipienttype constants to differentiate the type of addressee:


Message.addrecipient (type, address)


Here are the three constants of Message.recipienttype:

Message.RecipientType.TO

Message.RecipientType.CC

Message.RecipientType.BCC

So if we're going to send a message to the president and use a copy for the first lady, the following method will be used:


Address toaddress = new InternetAddress ("[email protected]");

Address ccaddress = new InternetAddress ("[email protected]");

Message.addrecipient (Message.RecipientType.TO, toaddress);

Message.addrecipient (Message.RecipientType.CC, ccaddress);


The JavaMail API does not provide a mechanism for checking the validity of email addresses. Of course we can do this by ourselves: Verify that the characters of the email address are written in the format specified by RFC822 or through MX records on the DNS server, and so on.


E. Authenticator

Like the Java.net class, the JavaMail API accesses protected resources by using the grantee Class (Authenticator) as a user name and password, where "resource" refers to the mail server. This JavaMail class (Authenticator) can be found in the Javax.mail package.

When using the abstract class authenticator, we must take the way of inheriting the abstract class, and the inheriting class must have a return Passwordauthentication object (the user name to use to store the authentication, Password) getpasswordauthentication () method. and to register in the session, the session will know which class to use for authentication.

The myauthenticator in the following code fragment is a subclass of authenticator.


Properties Props = new properties ();

Fill props with any information

Authenticator auth = new Myauthenticator ();

Session session = Session.getdefaultinstance (props, auth);


F. Transport

When sending a message, the transport class is used. This class implements the protocol that sends the message (called SMTP), which is an abstract class that we can use to send a message using the static method of this class, send ():


Transport.send (message);


Of course, the methods are diverse. We can also get the transport instance corresponding to the corresponding protocol by the session. And by passing the user name, password, mail server hostname and other parameters to establish a connection with the mail server, and use the SendMessage () method to send information, and finally close the connection:


Message.savechanges (); Implicit with Send ()

Transport Transport = Session.gettransport ("SMTP");

Transport.connect (host, username, password);

Transport.sendmessage (Message, message.getallrecipients ());

Transport.close ();


Comment: The method above is a good way to do this, especially if we are sending multiple messages on the same mail server. Because then we will send the mail after the connection to the mail server, and then close the connection. The basic method of send () is to connect to the mail server each time it is called, which is inefficient for sending multiple messages on the same mail server.

Note: If you need to monitor the Mail command during the sending process, you can set the debug flag before sending:


Session.setdebug (True).


G Store and folder

The session is very similar to receiving and sending mail. But after we get the session, we need to get a specific type of store from the session and then connect to the store, where the store represents the mail server where the mail is stored. In the process of connecting to the store, it is very possible to use a username, password, or authenticator.


Store store = Session.getstore ("IMAP");

Store store = Session.getstore ("POP3");

Store.connect (host, username, password);


After connecting to the store, a folder object, the directory object, is returned through the store's GetFolder () method, and we can read the message from this folder:


Folder folder = Store.getfolder ("INBOX");

Folder.open (folder.read_only);

Message message[] = Folder.getmessages ();


The above example first obtains the Inbox folder from the store (only one folder named Inbox is valid for the POP3 protocol), and then opens the folder as read-only (folder.read_only). Finally, the Getmessages () method of the folder is called to get an array of all the message in the directory.


Note: For the POP3 protocol, only one folder named Inbox is valid, and for the IMAP protocol, we can access multiple folder (think about the IMAP protocol above). and Sun took a smart approach when designing the Getmessages () method of the folder: first to receive a new mailing list, and then to read the message content from the mail server when needed (such as reading the contents of the message).

When reading a message, we can use the message class's GetContent () method to receive the message or the WriteTo () method to save the message, the GetContent () method only receives the message content (not including the message header), and the WriteTo () method will include the message header.


System.out.println (((mimemessage) message). GetContent ());


After reading the contents of the message, don't forget to close the folder and store.


Folder.close (Aboolean);

Store.close ();


The Boolean type parameter passed to the Folder.close () method indicates whether to update the folder after the action message is deleted.


H. Keep Moving!

After explaining the above seven Java Mail core class definitions and understanding the simple code snippets, the following sections will explain in detail how to use these classes to implement the advanced features of the JavaMail API.


V. Use of the JavaMail API

After clarifying how the core part of the JavaMail API works, I'll take you through some examples of using Java Mail API tasks.

1. Send mail

After getting the session, create and fill in the email message, and then send it to the mail server. This is the process of sending mail using the Java Mail API, before sending the message, we need to set up the SMTP server: By setting the properties of the Mail.smtp.host property.


String host = ...;

String from = ...;

String to = ...;


Get System Properties

Properties props = System.getproperties ();


Setup Mail Server

Props.put ("Mail.smtp.host", host);


Get session

Session session = Session.getdefaultinstance (props, null);


Define message

MimeMessage message = new MimeMessage (session);

Message.setfrom (New InternetAddress (from));

Message.addrecipient (Message.RecipientType.TO,

New InternetAddress (to));

Message.setsubject ("Hello JavaMail");

Message.settext ("Welcome to JavaMail");

Send message

Transport.send (message);


We need to put the above code into the TRY-CATCH structure block because of the possibility of throwing an exception in the process of creating the message and sending the message.


2. Receive mail

In order to read the mail, we get the session, and connect to the corresponding store in the mailbox, open the corresponding folder, and then get the message we want, of course, don't forget to close the connection at the end.


String host = ...;

String username = ...;

String password = ...;


Create Empty Properties

Properties Props = new properties ();


Get session

Session session = Session.getdefaultinstance (props, null);


Get the Store

Store store = Session.getstore ("POP3");

Store.connect (host, username, password);


Get folder

Folder folder = Store.getfolder ("INBOX");

Folder.open (folder.read_only);


Get Directory

Message message[] = Folder.getmessages ();


for (int i=0, n=message.length; i

SYSTEM.OUT.PRINTLN (i + ":" + message[i].getfrom () [0]

+ "\ T" + message[i].getsubject ());

}


Close Connection

Folder.close (FALSE);

Store.close ();


The code above does this by reading each message from the mailbox and displaying the sender address and subject of the message. Technically speaking, there is an anomaly: Getfrom () [0] throws an exception when the sender's address is empty.


The following code fragment effectively explains how to read the contents of the message, after displaying each message sender and subject, a user prompt will appear to get the user to read the confirmation of the message, if you enter Yes, we can use Message.writeto ( Java.io.OutputStream os) method to output the message content to the console, see JavaMail API for specific usage of message.writeto ().


BufferedReader reader = new BufferedReader (

New InputStreamReader (system.in));


Get Directory

Message message[] = Folder.getmessages ();

for (int i=0, n=message.length; i

SYSTEM.OUT.PRINTLN (i + ":" + message[i].getfrom () [0]

+ "\ T" + message[i].getsubject ());


System.out.println ("Does want to read message?" +

"[YES to Read/quit to end]");

String line = Reader.readline ();

if ("YES". Equals (line)) {

Message[i].writeto (System.out);

} else if ("QUIT". Equals (line)) {

Break

}

}


3. Delete messages and flags

Setting the flags associated with message is a common way to delete messages. These flags represent a number of system definitions and user-defined different states. Some flags are pre-defined in the flags class's internal class flag:

Flags.Flag.ANSWERED

Flags.Flag.DELETED

Flags.Flag.DRAFT

Flags.Flag.FLAGGED

Flags.Flag.RECENT

Flags.Flag.SEEN

Flags.Flag.USER

But you need to be aware of it: the presence of a flag does not imply that the flag is supported by all mail servers. For example, for an action to delete a message, the POP protocol does not support any of the above. So to determine which flags are supported--by accessing the Getpermanetflags () method of an already opened folder object, it returns the currently supported Flags class object.

When you delete a message, we can set the deleted flag for the message:


Message.setflag (Flags.Flag.DELETED, true);


But the first thing to do is open the folder using Read_write:


Folder.open (Folder.read_write);


When you close the folder after you delete the message, you need to pass a true as the erase acknowledgement for the deleted message.


Folder.close (TRUE);


Another way to delete messages in the folder class expunge () can also delete messages, but it does not support the POP3 implementation provided by Sun, and other third-party POP3 implementations support or do not support this approach.

In addition, a method for checking whether a flag is set is described: The Message.isset (Flags.flag flag) method, where the parameter is the checked flag.


4. Email authentication

We have previously learned how to use the authenticator class instead of using both the user name and password as arguments to the session.getdefaultinstance () or Session.getinstance () methods. In front of the small trial sledgehammer, now we will understand the comprehensive understanding of email authentication.

We are here to replace the direct use of the mail server hostname, user name, password, the three string as the way to connect to the POP3 store, using a property file that stores the mail server hostname information, and pass the session to the Custom authenticator instance:


Setup Properties

Properties props = System.getproperties ();

Props.put ("Mail.pop3.host", host);


Setup authentication, get session

Authenticator auth = new Popupauthenticator ();

Session session = Session.getdefaultinstance (props, auth);


Get the Store

Store store = Session.getstore ("POP3");

Store.connect ();


The Popupauthenticator class inherits the abstract class authenticator, and by overloading the authenticator class's getpasswordauthentication () The Passwordauthentication method returns a class object. The parameter param of the Getpasswordauthentication () method is a comma-separated string of user names and passwords.


Import javax.mail.*;

Import java.util.*;


public class Popupauthenticator extends Authenticator {


Public passwordauthentication getpasswordauthentication (String param) {

String username, password;


StringTokenizer st = new StringTokenizer (param, ",");

Username = St.nexttoken ();

Password = st.nexttoken ();


return new passwordauthentication (username, password);

}


}


5. Reply to a message

The way to reply to a message is simple: Use the reply () method of the message class to configure the recipient address and subject of the reply message (the system will default to "Re:" As the body of the message if no subject is provided), and there is no need to set up any message content. Just copy the sender or Reply-to to the new recipient. The Boolean parameter in the reply () method indicates whether to reply the message to the sender (the parameter value is false) or to everyone (the parameter value is true).

To add, reply-to addresses need to be set using the Setreplyto () method when sending a letter.


MimeMessage reply = (mimemessage) message.reply (false);

Reply.setfrom (New InternetAddress ("[email protected]");

Reply.settext ("Thanks");

Transport.send (reply);


6. Forward message

The process of forwarding a message is not as simple as the previous reply message, it will create a forward message, which is not a method to do.

Each message is made up of multiple parts, each part called a Message body section, a BodyPart class object, and a MimeBodyPart class object for MIME-type messages. These message bodies are contained in containers that become multipart and are Mimemultipart class objects for MIME-type messages. When forwarding a message, we set up a text message body section and a forwarded text message body section, and then put the two message bodies into a multipart. Note that copying one message content to another is only a DataHandler (data processor) copy of it. This is a class defined by the JavaBeans Activation framework that provides access to operational commands for message content, manages message content operations, and is a consistent interface between different data sources and data formats.


Create the message to forward

Message forward = new MimeMessage (session);


Fill in Header

Forward.setsubject ("FWD:" + message.getsubject ());

Forward.setfrom (New InternetAddress (from));

Forward.addrecipient (Message.RecipientType.TO,

New InternetAddress (to));


Create your new Message part

BodyPart Messagebodypart = new MimeBodyPart ();

Messagebodypart.settext (

"Here's go with the original message:\n\n");


Create a multi-part to combine the parts

Multipart Multipart = new Mimemultipart ();

Multipart.addbodypart (Messagebodypart);


Create and fill part for the forwarded content

Messagebodypart = new MimeBodyPart ();

Messagebodypart.setdatahandler (Message.getdatahandler ());


ADD part to multi part

Multipart.addbodypart (Messagebodypart);


Associate multi-part with Message

Forward.setcontent (multipart);


Send message

Tran


Java API Interpretation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.