Javamail (Java Mail Service) API (1)

Source: Internet
Author: User
Tags imap nntp rfc mx record microsoft outlook
1. Introduction to javamail API
Javamail API is used to read, write, and send electronic messages.
Information. We can use it to create Mail User agents such as Eudora, Foxmail, and MS Outlook Express.
(Mail User Agent (Mua ). Instead of mail transfer agent
In this way, the MTA program can send, deliver, and forward emails. From another perspective, our email users use the Mua program to read and write emails, while Mua relies on the MTA to process emails.
Send.
After understanding the relationship between Mua and MTA, let's see how the javamail API provides the information access function! The javamail API is designed to send and receive electronic information in a protocol-independent manner. This API is divided into two parts:

Basic Function: This article describes how to send and receive electronic information in a way that does not rely on protocols. However, we will see that this is only wishful thinking.
The second part depends on specific protocols, such as SMTP, Pop, IMAP, and nntp. The javamail API in this section aims to communicate with the server and is not included in this article.

Ii. Related Protocols
Before entering the javamail API, let's take a look at the protocols involved in the API. The following are the four major information transmission protocols that everyone knows and is willing to use:
SMTP
Pop
IMAP
Mime
When
However, not all of the above four protocols are available, and NNTP and other protocols can be used to transmit information. However, this article does not mention these protocols because they are not often used. Understanding these four basic protocols will help us better
Use the javamail API. However, javamail APIs are designed to be protocol-independent. Currently, we cannot overcome these constraints. Specifically, if we use
If the function is not supported by the selected protocol, the javamail API cannot be magic like a magician.

1. SMTP
Simple Mail
The transfer protocol defines the mail delivery mechanism. In the following section, we will use a Java-mail-based program to communicate with the SMTP server of the Company or ISP. This SMTP server will mail
To the SMTP server of the receiver until it is finally obtained by the receiver through pop or imap protocol. This does not require the SMTP server to use mail forwarding that supports authorization, but you must note that
Set the SMTP server correctly (the setting of the SMTP server is irrelevant to the javamail API ).

2. Pop
Pop is a Post Office Protocol.
Three versions, known as POP3. Pop defines a mechanism for users to obtain emails. It specifies that each user uses a separate mailbox. The features most people are familiar with when using pop and
Not all are supported, for example, viewing the number of new emails in the mailbox. This function is built in Microsoft Outlook, so it indicates that the mail client software such as Microsoft Outlook is queried
To calculate the number of new emails to implement the aforementioned functions. Therefore, when using the javamail API, you must note that when you need to obtain information such as the number of new emails mentioned above,
We have to perform computation on our own.

3. imap
IMAP is used in the Advanced Protocol for receiving information. The current version is version 4th, so it is also called IMAP4. Note:
When using IMAP, the mail server must support this protocol. In this regard, we cannot completely use IMAP to replace pop, and we cannot expect IMAP to be supported anywhere. Assume that mail
The server supports IMAP, so our mail program will be able to have the following features supported by IMAP: each user may have multiple directories on the server, these directories can be shared among multiple users.
Its
It is more advanced than pop, but when trying to adopt IMAP, we realize that it is not perfect: Because IMAP needs to receive new information from other servers, it delivers the information
Users maintain multiple directories for each user, which brings high load to the mail server. In addition, the difference between IMAP and pop is that pop users will download emails from the email server when receiving emails,
IMAP allows users to directly access the mail directory. Therefore, when backup jobs are performed on the mail server, the mail directory used by each user who has been using the mail system for a long time occupies a large space, this will directly cause
Disk Space on the email server has soared.

4. Mime
Mime is not a protocol used to send mail. It defines the format of mail content as an extension of multi-purpose mail: Information
Format, attachment format, and so on. Some RFC standards involve MIME: RFC 822, RFC 2045, RFC 2046, and RFC 2047.
You can read matrixer. As a javamail API developer, we do not need to care about these format definitions, but these formats are used in programs.

5. nntp and other third-party protocols
Because javamail API is designed to separate the provider from a third-party protocol, we can easily add some third-party protocols. Sun maintains a list of third-party protocol implementation providers: vendor.

Iii. Installation
1. Install javamail
To use the javamail API, you need to add the mail. jar file to the classpath from the keystore (this file includes the javamail implementation. This implementation provides support for SMTP, IMAP4, and POP3.
Note: after installing the javamail implementation, we will find many interesting simple instance programs in the demo directory.
In
After javamail is installed, we also need to install the JavaBeans activation framework, because this framework is the javamail API
Yes. If we use J2EE, we do not need to download javamail separately because it exists in J2EE. jar, and we only need to add J2EE. jar
Classpath.

2. Install JavaBeans activation framework
From http://java.sun.com/products/javans/glasgow/jaf.html
Load JavaBeans activation framework and add it to classpath. This framework adds the classification of any data blocks and
Features. These features are required by the javamail API. Although it sounds like these features are very vague, it only provides basic information for our javamail API.
Mime Type supported.
So far, we should add both mail. jar and activation. jar to classpath.
Of course, from a convenient perspective, you can copy these two jar files to the lib/EXT directory of the JRE directory.

4. Get to know javamail API for the first time
1. understand our javamail Environment
A. view the javamail core Class Structure
Dozen
Open the javamail. jar file and we will find that some core classes exist under the javax. mail package: Session, message, address,
Authenticator, transport, store, and folder. In addition, there are some common subclasses in the javax. Mail. Internet package.
B. Session
The session class defines basic mail sessions. Just like an http session, our work of sending and receiving emails is based on this session. The Session object uses the java. util. properties object to obtain the information shared by the mail server, user name, password, and the entire application.
The session class construction method is private, so we can use the getdefaultinstance () Static factory method provided by the session class to obtain a default session object:
Properties props = new properties (); // fill props with any informationsession session = session. getdefaultinstance (props, null );
Or use the static factory method getinstance () to get the custom session:
Properties props = new properties (); // fill props with any informationsession session = session. getinstance (props, null );
From the above two examples, it is not difficult to find that the second parameter of the getdefaultinstance () and getinstance () methods is null, because in the above example, email authorization is not used, authorization is described in detail below.
From the perspective of many instances, it is sufficient to use the shared session when accessing the mail server, even in the mode of multiple user mailboxes.

C. Message
When
After the session object is created, the constructor information body can be sent. Here, Sun provides the message type to help developers complete this task. Because the message is
Abstract classes. In most cases, we use the javax. Mail. Internet. mimemessage subclass, which uses the MIME type and mime information header.
Email information. The information header can only use US-ASCII characters, not ASCII characters are used by encoding to ASCII.
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: For the mimemessage class, there are multiple constructor methods, such as using the input stream as the parameter constructor.

After creating a mimemessage object, we need to set each part of the object. For the mimemessage class, these parts are mimepart interfaces. The most basic method to set the information content is to call the setcontent () method by indicating the information content and meter type parameters:
Message. setcontent ("hello", "text/plain ");
However, if the message content 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 above are more suitable for text information. For other information types, such as HTML information, use the former.
Don't forget. Use setsubject () to set the mail subject for the mail:
Message. setsubject ("first ");

D. Address
Here, we have created a session and message. The following describes how to use the mail address class: address. Like 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 email address, we can create an email address class:
Address = new internetaddress ("president@whitehouse.gov ");
To add a name after the email address, you can create an email address class with the email address and name by passing two parameters: representing the email address and name string:
Address = new internetaddress ("president@whitehouse.gov", "George Bush ");
The mail address class mentioned in this article is prepared to set the mail sender and receiver of the Mail Information. After the mail address class is established, we use setfrom () and setreplyto () of the message () you can set the mail sender in either of the following ways:
Message. setfrom (Address); message. setreplyto (Address );
If multiple sender addresses exist in the email, you can use addform () to add the sender:
Address [] =...; message. addfrom (Address );
To set the recipient, we use the addrecipient () method to add the recipient. This method requires the constant message. recipienttype to distinguish the recipient type:
Message. addrecipient (type, address)
The following are the three constants of message. recipienttype:
Message. recipienttype.
Message. recipienttype. CC
Message. recipienttype. bcc
Therefore, if we want to send an email to the President and send a copy to the First Lady, the following method will be used:
Address toaddress = new internetaddress ("vice.president@whitehouse.gov"); Address ccaddress = new internetaddress ("first.lady@whitehouse.gov"); message. addrecipient (message. recipienttype. to, toaddress); message. addrecipient (message. recipienttype. CC, ccaddress );
The javamail API does not provide a mechanism to check the validity of the email address. Of course, we can do this by ourselves: verify whether the mail address characters are written in the format specified by rfc822 or pass the MX record verification on the DNS server.

E. authenticator
Image
In the same way as the java.net class, the javamail API uses the authenticator class to access the protected resources by using the user name and password.
"Resource" refers to the mail server. In the javax. mail package, you can find the javamail Authorizer class (authenticator ).
In use
When the abstract class authenticator is used, we must inherit the abstract class, And the inherited class must have the returned passwordauthentication object.
(Used to store the user name and password used for authentication) getpasswordauthentication () method. And register in the session to make
Session can be used to know which class to use during authentication.
In the following code snippet, myauthenticator is a subclass of authenticator.
Properties props = new properties (); // fill props with any informationauthenticator auth = new myauthenticator (); Session session = session. getdefaultinstance (props, auth );

Related Article

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.