Receive e-mail messages from a POP3-IMAP server
This article walks through steps to download e-mail messages from a POP3/IMAP server’s inbox, using JavaMail API. The following picture depicts how messages are logically stored on the server:
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.
Speaking of JavaMail API‘s language, it provides three corresponding classes: Store, Folder and Message.
- A Store object can be obtained from the current session by invoking the method getStore(String protocol)of Session class. Connecting to the Store by calling its method connect(String user, String pass), disconnecting by calling its close() method.
- A Folder object can be obtained from the store by invoking the getFolder(String folderName) method. For a regular mail box, the folder name must be “inbox” (case-insensitive). The most important methods of the Folderclass are:
- open(int mode): Opens the folder either in READ_ONLY mode or READ_WRITE mode.
- getMessages(): Retrieves an array of Message objects which are marked un-read in the folder. A Message object may be a lightweight reference, and its detailed content will be filled up on demand.
- close(boolean expunge): Closes the folder, and permanently remove all messages which are marked delete, if expunge is true.
- A Message object represents an e-mail message. To get detailed attributes of a message, the following methods can be called on the Message object:
- Address getFrom(): returns a list of senders in From attribute of the message.
- Address getRecipients(Message.RecipientType type): gets recipient addresses of the message, type can be either TO or CC.
- String getSubject(): gets subject of the message.
- Date getSentDate(): gets date and time when the message was sent.
- Object getContent(): gets content of the message.
Typically, the steps to connect to a server and download new e-mail messages are as follows:
- Prepare a Properties object which holds server settings such as host, port, protocol…
- Create a session to initiate a working session with the server.
- Obtain a store from the session by a specific protocol (IMAP or POP3). IMAP is recommended.
- Connect to the store using a credential (username and password).
- Gets inbox folder from the store.
- Open the inbox folder.
- Retrieve messages from the folder.
- Fetch details for each message.
- Close the folder.
- Close the store.
Recommended Book: JavaMail API
And following is code of a sample program: