import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
/**
* Demonstrate POP mail using JavaMail. Requires mail.jar activation.jar
* Sample run: java -cp .;mail.jar;activation.jar PopMail
**/
public class PopMail
{
public static void main(String args[]) throws Exception
{
String pop3Host="myhost.com", popUser="john", popPassword="letmein";
Session session = Session.getDefaultInstance(System.getProperties(), null);
Store store = session.getStore("pop3");
store.connect(pop3Host, -1, popUser, popPassword);
// Open the default folder
Folder folder = store.getDefaultFolder();
if (folder == null)
throw new NullPointerException("No default mail folder");
folder = folder.getFolder("INBOX");
if (folder == null)
throw new NullPointerException("Unable to get folder: " + folder);
// Get message count
folder.open(Folder.READ_WRITE);
int totalMessages = folder.getMessageCount();
if (totalMessages == 0)
{
System.out.println("No messages found in inbox");
folder.close(false);
store.close();
return;
}
// Get attributes & flags for all messages
Message[] messages = folder.getMessages();
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.FLAGS);
fp.add("X-Mailer");
folder.fetch(messages, fp);
// Process each message
for (int i = 0; i < messages.length; i++)
{
if (!messages[i].isSet(Flags.Flag.SEEN))
process(messages[i]);
//messages[i].setFlag(Flags.Flag.DELETED, true);
}
folder.close(true);
store.close();
}
private static void process(Message message)
throws Exception
{
System.out.println("subject: " + message.getSubject()
+ ", sent: " + message.getSentDate()
+ ", size: " + message.getSize());
}
}