10.17. Checking a POP3 Mailbox
Problem
You need to check a POP3 mailbox.
Solution
Use Commons Net POP3Client to check a POP3 mailbox
for incoming mail. The following example connects to the
POP3
server www.discursive.com, logs in as
tobrien@discursive.com, and prints each message in
the mailbox:
import org.apache.commons.io.CopyUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.pop3.POP3Client;
import org.apache.commons.net.pop3.POP3MessageInfo;
POP3Client client = new POP3Client( );
client.connect("www.discursive.com");
client.login("tobrien@discursive.com", "secretpassword");
POP3MessageInfo[] messages = client.listMessages( );
for (int i = 0; i < messages.length; i++) {
int messageNum = messages[i].number;
System.out.println( "************* Message number: " + messageNum );
Reader reader = client.retrieveMessage( messageNum );
System.out.println( "Message:\n" + IOUtils.toString( reader ) );
IOUtils.closeQuietly( reader );
}
client.logout( );
client.disconnect( );This example calls client.listMessage()
to get an array of
POP3MessageInfo objects. Each message is retrieved
using the message number contained in each
POP3MessageInfo. To retrieve the contents of an
individual message, the message number is passed to
retrieveMessage()
, which returns a Reader
from which the message body is read. The previous example prints the
contents of a POP3 mailbox, as shown below:
************* Message number: 1 Message: Return-Path: <jerk@spamheaven.net> X-Original-To: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access