In this phrase, we connect to a POP3 email server and retrieve all messages in the INBOX folder. The JavaMail API makes this task quite easy to perform. Here are the general steps you perform when using the JavaMail API to read messages from a POP mail server:
In the phrase, we get a default instance of the Session object using the getdefaultInstance() static method. The Session object represents a mail session. With the Session object, we then get a Store object that implements the POP3 protocol. The Store object represents a message store and its access protocol. If, for example, we wanted to connect to an IMAP mail server instead of a POP3 server, we could change this line of code to get an IMAP store instead of the POP3 store. We'd also have to include an additional JAR file that supports the IMAP protocol. Sun provides the imap.jar file as part of the JavaMail distribution. We connect to a POP3 store by calling the connect() method of the Store object and passing a host, username, and password. In the remainder of the phrase, we retrieve the INBOX folder and all the messages contained within it. We print the message sender (From), the message subject, and the first 100 characters of the message body for each message in the INBOX folder. The Folder class also contains a list() method, which we do not use in this phrase, but can be used to obtain an array of Folder objects representing all the sub-folders of the folder on which it is called. So, for example, if the INBOX folder had many sub-folders, we could obtain a reference to each of those using the following code: Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); Folder[] subfolders = folder.list(); The subfolders array in this example would contain a Folder object for each sub-folder under the INBOX folder. We could then process the messages in each of those, just as we did for the messages contained in the INBOX folder. There is also a getFolder() method on the Folder class, which takes a single string parameter and returns a folder with a name matching the string passed in. Using the Folder class, you could write a method that traversed an entire email account and read all messages contained in all of the user's folders. |