Wednesday, June 17, 2009

Simple Java Mail Pop 3 client

import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

public class POP3Client {

public static void main(String args[]) throws Exception {
String host = "your_mail_server_ip";

// Get system properties
Properties props = System.getProperties();


Session session = Session.getDefaultInstance(props, null);

// Get the store
Store store;
store = session.getStore("pop3");
store.connect(host, "xxx@abc.com", "password");

// Get inbox folder

Folder folder = store.getDefaultFolder().getFolder("INBOX");
folder.open(Folder.READ_WRITE);


// Get directory
Message message[] = folder.getMessages();
for (int i = 0, n = message.length; i < n; i++) {

System.out.println(i + ": Subject" + message[i].getFrom()[0] + "\t"
+ message[i].getSubject());
String content = message[i].getContent();


System.out.print(content);
//This will delete the mail from the inbox after you close the folder
message[i].setFlag(Flags.Flag.DELETED, true);
}

// Close connection
folder.close(true);
store.close();

}

}

2 comments:

Long said...

I have some problem with delete message. The message still in inbox after I run the program. Can you help me ?

Dinuka Arseculeratne said...

Hi Long,
Did you run the same code as above? What mail server are you trying to connect to?

Post a Comment

 
;