While working on a Java application, I found the need for a simple Java mailbox reader. I wanted to be able to scan through one of my POP/POP3 mailboxes for messages, and then do something with those messages.
To that end I created the following example JavaMail POP mailbox reader. It connects to a standard POP/POP3 mailbox, then scans through all the messages in the "Inbox" folder.
One word of caution: If your email inbox is large, this program may run for a very long time, because it reads every email message on your POP mail server. As a result, I've put a check inside the for loop below so it will only print the first ten email messages. Once you're comfortable with how this JavaMail program works, you can remove that limit.
Without any further introduction, here's my JavaMail POP reader program:
package javamailtests; import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class JavaMailPop3Reader { public static void main(String args[]) throws Exception { // mail server connection parameters String host = "pop.mail.yahoo.com"; String user = "USERNAME"; String password = "PASSWORD"; // connect to my pop3 inbox Properties properties = System.getProperties(); Session session = Session.getDefaultInstance(properties); Store store = session.getStore("pop3"); store.connect(host, user, password); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); // get the list of inbox messages Message[] messages = inbox.getMessages(); if (messages.length == 0) System.out.println("No messages found."); for (int i = 0; i < messages.length; i++) { // stop after listing ten messages if (i > 10) { System.exit(0); inbox.close(true); store.close(); } System.out.println("Message " + (i + 1)); System.out.println("From : " + messages[i].getFrom()[0]); System.out.println("Subject : " + messages[i].getSubject()); System.out.println("Sent Date : " + messages[i].getSentDate()); System.out.println(); } inbox.close(true); store.close(); } }
To be clear, this JavaMail example program is intended to show you how to loop through all messages in a POP/POP3 mailbox, such as my inbox. As a result, you may end up with a very large list of email messages.
I just tested this with my Yahoo Mail account, and can confirm that it works. (One word of caution about Yahoo: I think you can only use the POP protocol with "premium" Yahoo email accounts.)
To trim this list of messages down quite a bit, you can add search criteria to your JavaMail program. I'll demonstrate this in future JavaMail search examples.