Javamail Api 简明教程
JavaMail API - Core Classes
JavaMail API 包含一些接口和类,用于发送、读取和删除电子邮件。虽然 JavaMail API 中有许多包,但会涵盖 Java Mail API 中经常使用的两个主要包:javax.mail 和 javax.mail.internet 包。这些包包含所有 JavaMail 核心类。它们是:
The JavaMail API consists of some interfaces and classes used to send, read, and delete e-mail messages. Though there are many packages in the JavaMail API, will cover the main two packages that are used in Java Mail API frequently: javax.mail and javax.mail.internet package. These packages contain all the JavaMail core classes. They are:
Class |
Description |
The key class of the API. A multithreaded object represents the connection factory. |
|
An abstract class that models an e-mail message. Subclasses provide the actual implementations. |
|
An abstract class that models the addresses (from and to addresses) in a message. Subclasses provide the specific implementations. |
|
An abstract class used to protect mail resources on the mail server. |
|
An abstract class that models a message transport mechanism for sending an e-mail message. |
|
An abstract class that models a message store and its access protocol, for storing and retrieving messages. A Store is divided into Folders. |
|
An abstract class that represents a folder of mail messages. It can contain subfolders. |
|
javax.mail.internet.MimeMessage |
Message is an abstract class, hence must work with a subclass; in most cases, you’ll use a MimeMessage. A MimeMessage is an e-mail message that understands MIME types and headers. |
javax.mail.internet.InternetAddress |
This class represents an Internet email address using the syntax of RFC822. Typical address syntax is of the form user@host.domain or Personal Name <user@host.domain>. |
让我们详细学习这些类中的每一个类,在后续章节中,我们将学习使用每一个类的示例。
Let us study each of these classes in detail and in the subsequent chapters we shall study examples using each of these.
Session Class
Session 类是 JavaMail API 的主要类,它没有子类。Session 对象充当 JavaMail API 的连接工厂,它处理配置设置和身份验证。
The Session class is the primary class of the JavaMail API and it is not subclassed. The Session object acts as the connection factory for the JavaMail API, which handles both configuration setting and authentication.
可以通过以下方式创建 Session 对象:
Session object can be created in the following ways:
-
By looking up the administered object stored in the JNDI service InitialContext ctx = new InitialContext(); Session session = (Session) ctx.lookup("usersMailSession"); usersMailSession is the JNDI name object used as the administered object for the Session object. usersMailSession can be created and configured with the required parameters as name/value pairs, including information such as the mail server hostname, the user account sending the mail, and the protocols supported by the Session object.
-
Another method of creating the Session object is based on the programmatic approach in which you can use a java.util.Properties object to override some of the default information, such as the mail server name, username, password, and other information that can be shared across your entire application.
Session 类的构造函数是私有的。因此,Session 类提供了两个方法(如下所示)来获取 Session 对象。
The constructor for Session class is private. Hence the Session class provides two methods (listed below) which get the Session object.
-
getDefaultInstance(): There are two methods to get the session object by using the getDefaultInstance() method. It returns the default session. public static Session getDefaultInstance(Properties props) public static Session getDefaultInstance(Properties props,Authenticator auth)
-
getInstance(): There are two methods to get the session object by using the getInstance() method. It returns the new session. public static Session getInstance(Properties props) public static Session getInstance(Properties props,Authenticator auth)
Message Class
创建 Session 对象后,我们现在继续创建一个要发送的消息。消息类型将是 javax.mail.Message。
With Session object created we now move on to creating a message that will be sent. The message type will be javax.mail.Message.
-
Message is an abstract class. Hence its subclass javax.mail.internet.MimeMessage class is mostly used.
-
To create the message, you need to pass session object in MimeMessage class constructor. For example: MimeMessage message=new MimeMessage(session);
-
Once the message object is created we need to store information in it. Message class implements the javax.mail.Part interface while javax.mail.internet. MimeMessage implements javax.mail.internet.MimePart. You can either use message.setContent() or mimeMessage.setText() to store the content.
-
Commonly used methods of MimeMessage class are MethodDescriptionpublic void setFrom(Address address)used to set the from header field.public void addRecipients(Message.RecipientType type, String addresses)used to add the given address to the recipient type.public void setSubject(String subject)used to set the subject header field.public void setText(String textmessage)used to set the text as the message content using text/plain MIME type.
Address Class
现在,既然我们有了 Session 和 Message(其中存储了内容)对象,我们需要使用 Address 对象来写信。
Now that we have a Session and Message (with content stored in it) objects, we need to address the letter by using Address object.
-
Address is an abstract class. Hence its subclass javax.mail.internet.InternetAddress class is mostly used.
-
Address can be created by just passing email address: Address address = new InternetAddress("manisha@gmail.com");
-
Another way of creating Address is by passing name alogwith the email address: Address address = new InternetAddress("manisha@gmail.com", Manisha);
-
You can also set the To, From, CC, BCC fields as below message.setFrom(address) message.addRecipient(type, address) Three predefined address types are objects with one of these values: Message.RecipientType.TO Message.RecipientType.CC Message.RecipientType.BCC
Authenticator Class
Authenticator 类表示一个知道如何为网络连接获取身份验证的对象。它通常会向用户提示信息来执行此操作。
The class Authenticator represents an object that knows how to obtain authentication for a network connection. Usually, it will do this by prompting the user for information.
-
Authenticator is an abstract class. You create a subclass PasswordAuthentication, passing a username and password to its constructor.
-
You must register the Authenticator with the Session when you create session object.
以下是 Authenticator 用法的示例:
Following is an example of Authenticator use:
Properties props = new Properties();
//Override props with any customized data
PasswordAuthentication auth = new PasswordAuthentication("manisha", "pswrd")
Session session = Session.getDefaultInstance(props, auth);
Transport Class
Transport 类用作消息传输机制。此类通常使用 SMTP 协议发送消息。
Transport class is used as a message transport mechanism. This class normally uses the SMTP protocol to send a message.
-
It is an abstract class.
-
You can use the default version of the class by just calling the static send() method: Transport.send(message);
-
The other way to send message is by getting a specific instance from the session for your protocol, pass along the username and password (blank if unnecessary), send the message, and 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();
Store Class
一个抽象类,用于对消息存储及其访问协议进行建模,以便存储和检索消息。子类提供实际实现。Store 扩展 Service 类,它为命名存储、连接到存储和侦听连接事件提供了许多常见方法。
An abstract class that models a message store and its access protocol, for storing and retrieving messages. Subclasses provide actual implementations. Store extends the Service class, which provides many common methods for naming stores, connecting to stores, and listening to connection events.
客户端通过获取实现数据库访问协议的 Store 对象来访问消息存储。大多数消息存储要求用户在允许他们访问之前进行身份验证。connect 方法执行该身份验证。
Clients gain access to a Message Store by obtaining a Store object that implements the database access protocol. Most message stores require the user to be authenticated before they allow access. The connect method performs that authentication.
Store store = session.getStore("pop3");
store.connect(host, username, password);
Folder Class
Folder 是一个抽象类,表示邮件消息的文件夹。子类实现特定于协议的文件夹。文件夹既可以包含子文件夹,也可以包含消息,从而提供层次结构。
Folder is an abstract class that represents a folder for mail messages. Subclasses implement protocol specific Folders. Folders can contain subfolders as well as messages, thus providing a hierarchical structure.
连接到 Store 之后,您可以获取一个文件夹,必须先对其进行打开,然后才能从中读取消息。
After connecting to the Store, you can then get a Folder, which must be opened before you can read messages from it.
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message message[] = folder.getMessages();
文件夹对象的 getFolder(String name) 方法返回命名的子文件夹。阅读邮件完成后,关闭存储和文件夹连接。
The getFolder(String name) method for a Folder object returns the named subfolder. Close the both the Store and Folder connection once reading mail is done.
我们可以在下图中看到 Store 和 Folder 的关系:
We can see the Store and Folder relation the image below:
正如我们所看到的,对于每个用户帐户,服务器都有一个存储,它是用户消息的存储。该存储被划分为文件夹,“收件箱”文件夹是主要文件夹,其中包含电子邮件消息。文件夹既可以包含消息,也可以包含子文件夹。
As we can see, for each user account, the server has a store which is the storage of user’s messages. The store is divided into folders, and the “inbox” folder is the primarily folder which contains e-mail messages. A folder can contain both messages and sub-folders.