import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
public class POP3Client {
public static void main(String[] args) {
Properties props = new Properties();
String host = "utopia.poly.edu";
String username = "eharold";
String password = "mypassword";
String provider = "pop3";
try {
// Connect to the POP3 server
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore(provider);
store.connect(host, username, password);
// Open the folder
Folder inbox = store.getFolder("INBOX");
if (inbox == null) {
System.out.println("No INBOX");
System.exit(1);
}
inbox.open(Folder.READ_ONLY);
// Get the messages from the server
Message[] messages = inbox.getMessages();
for (int i = 0; i < messages.length; i++) {
System.out.println("------------ Message " + (i+1)
+ " ------------");
messages[i].writeTo(System.out);
}
// Close the connection
// but don't remove the messages from the server
inbox.close(false);
store.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void printMessage(Message m) throws Exception {
// Print the message header
Address[] from = m.getFrom();
if (from != null) {
for (int i = 0; i < from.length; i++) {
System.out.println("From: " + from[i]);
}
}
Address[] to = m.getRecipients(Message.RecipientType.TO);
if (to != null) {
for (int i = 0; i < to.length; i++) {
System.out.println("To: " + to[i]);
}
}
String subject = m.getSubject();
if (subject != null) {
System.out.println("Subject: " + subject);
}
Date d = m.getSentDate();
if (d != null) {
System.out.println("Date: " + d);
}
// Print a blank line to separate the header from the body
System.out.println();
// Print the message body
Object content = m.getContent();
if (content instanceof String) {
System.out.println(content);
}
else if (content instanceof InputStream) {
InputStream in = (InputStream) content;
int c;
while ((c = in.read()) != -1) System.out.write(c);
}
else {
// This is actually likely to be a multi-part MIME
// message. We'll cover this in a later example.
System.out.println("Unrecognized Content Type");
}
}
} |