Javamail (Java Mail Service) API (2)

Source: Internet
Author: User
Tags imap

F. Transport
The transport class will be used when sending information. This class implements the message sending Protocol (SMTP). This class is an abstract class. We can use this class's Static Method Send () to send messages:
Transport. Send (Message );
Of course, there are various methods. We can also obtain the transport instance corresponding to the Protocol from the session. Connect to the mail server by passing parameters such as the user name, password, and mail server host name, send the information using sendmessage (), 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 ();
Rating
Theory: the above method is a good method, especially when we send multiple emails on the same email server. This is because we will send emails continuously after connecting to the mail server, and then close the connection.
The basic method of sending () is to connect to the mail server at each call, which is inefficient for sending multiple emails on the same mail server.
Note: If you need to monitor the MAIL command during mail sending, you can set the debug flag before sending:
Session. setdebug (true ).

G. Store and folder
Connect
Session is used for receiving and sending emails. However, after obtaining the session, we need to obtain a specific type of store from the session, and then connect
Store, where store represents the mail server that stores emails. The user name, password, or authenticator is very likely to be used in the process of connecting to the store.
// Store = session. getstore ("IMAP"); store = session. getstore ("POP3"); store. Connect (host, username, password );
After connecting to store, a folder object, that is, the directory object, will be returned through the getfolder () method of store. We can read the mail information from this folder:
Folder folder = store. getfolder ("inbox"); folder. Open (Folder. read_only); message [] = folder. getmessages ();
Upper
In this example, the inbox folder is obtained from the store (only one folder named inbox is valid for POP3 protocol), and then read-only
(Folder. read_only) to Open folder, and finally call the getmessages () method of folder to get the number of all messages in the directory
Group.

Note: For POP3 protocol, only one folder named inbox is valid, while for imap protocol, we can access Multiple folder (think about the previous article)
Imap protocol ). Sun also uses a smart method when designing the getmessages () method of Folder: first receives the New Mail list, And then when necessary (such as reading
To read the content of the email from the email server.
When reading an email, we can use the getcontent () method of the message class to receive the email or the writeto () method to save the email. getcontent () the method only receives the mail content (excluding the mail header), while the writeto () method includes the mail header.
System. Out. println (mimemessage) Message). getcontent ());
After reading the mail content, do not forget to close folder and store.
Folder. Close (distinct lean); store. Close ();
The boolean type parameter passed to the folder. Close () method indicates whether to update folder after the operation email is deleted.

H. Proceed!
After explaining the definition and understanding of the above seven Java mail core classes and the simple code snippets, the following describes in detail how to use these classes to implement the advanced functions required by the javamail API.

5. Use javamail API
After clarifying how the core part of the javamail API works, I will guide you through some examples of using Java mail API tasks.
1. Send email
After obtaining the session, create and fill in the mail information, and then send it to the mail server. This is the process of sending mail using the Java mail API. before sending the mail, we need to set the SMTP server by setting the mail. SMTP. Host attribute of properties.
String host = ...; string from = ...; string to = ...; // get system propertiesproperties props = system. getproperties (); // setup mail serverprops. put ("mail. SMTP. host ", host); // get Sessionsession session = session. getdefaultinstance (props, null); // define messagemimemessage 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 messagetransport. send (Message );
Because an exception may be thrown during the process of setting up the mail Information and sending the mail, we need to put the above Code into the try-catch structure block.

2. receive emails
In order to read the mail, we get the session, connect to the corresponding store of the mailbox, open the corresponding folder, and then get the mail we want. Of course, don't forget to close the connection at the end.
String host = ...; string username = ...; string Password = ...; // create empty propertiesproperties props = new properties (); // get Sessionsession session = session. getdefaultinstance (props, null); // get the storestore store = session. getstore ("POP3"); store. connect (host, username, password); // get folderfolder folder = store. getfolder ("inbox"); folder. open (folder. read_only); // get directorymessage message [] = folder. getmessages (); For (INT I = 0, n = message. length; I
The code above reads each email from the mailbox and displays the mail sender's address and subject. Technically speaking, an exception may exist: When the sender address is blank, getfrom () [0] throws an exception.

Lower
The code snippet below effectively describes how to read the mail content. After each mail sender and topic are displayed, a user prompt is displayed to confirm whether the user has read the email. If yes is entered, we
The message. writeto (Java. Io. outputstream OS) method can be used to output the mail content to the console.
For the specific usage of message. writeto (), see javamail API.
Bufferedreader reader = new bufferedreader (New inputstreamreader (system. in); // get directorymessage message [] = folder. getmessages (); For (INT I = 0, n = message. length; I
3. delete emails and logos
Setting the message-related flags is a common method for deleting emails. These flags indicate different States defined by the system and user. Some flags are pre-defined in the internal flag of the flags class:
Flags. Flag. answered
Flags. Flag. Deleted
Flags. Flag. Draft
Flags. Flag. Flagged
Flags. Flag. Recent
Flags. Flag. Seen
Flags. Flag. User
However
Note: The flag does not mean that it is supported by all email servers. For example, for mail deletion, the POP protocol does not support any of the above operations. So determine which
The flag is supported ?? By accessing the getpermanetflags () method of an opened folder object, it returns the currently supported flags class object.
When deleting an email, we can set the mail's deleted flag:
Message. setflag (flags. Flag. Deleted, true );
However, you must first use read_write to Open folder:
Folder. Open (Folder. read_write );
When you disable folder after deleting an email, you must pass a "true" message to confirm the deletion.
Folder. Close (true );
In the folder class, expunge () can also delete emails, but it is not supported by Sun's POP3 implementation, other third-party POP3 implementations support or do not support this method.
In addition, this article introduces a method to check whether a flag is set: Message. isset (flags. flag Flag) method. The parameter is the flag to be checked.

4. Email Authentication
Me
We have learned how to use the authenticator class instead of using the user name and password strings
Parameters of the Session. getdefainstance instance () or session. getinstance () method. After the previous test, we will
Learn about email authentication.
Instead of directly using the mail server host name, user name, and password strings as the method to connect to the POP3 store, we use the attribute file that stores the mail server host name information, the user-defined authenticator instance is imported when the session is obtained:
// Setup propertiesproperties props = system. getproperties (); props. put ("mail. pop3.host ", host); // setup authentication, get sessionauthenticator auth = new popupauthenticator (); Session session = session. getdefaultinstance (props, auth); // get the storestore store = session. getstore ("POP3"); store. connect ();

Popupauthenticator
Class inherits the abstract class authenticator, and returns
Returns the passwordauthentication class object. The param parameter of the getpasswordauthentication () method is separated by commas (,).
A string consisting of a user name and a password.
Import javax. mail. *; import Java. util. *; public class 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 );}}


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.