Access GMail with imap using java mail api

24 01 2009

I had to search through quite a few web pages for this. So I am putting it here for future reference. My conscience pricks for putting all the code in main method. But I guess this is an exception. :)

import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

public class InboxReader {

public static void main(String args[]) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>", "password");
System.out.println(store);

Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
System.out.println(message);
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}

}

}

UPDATE: Below update is from the Niteesh Bhargava’s comment. Thanks Niteesh.

Above code won’t work always :

Folder outbox = store.getFolder(”[Gmail]/Sent Mail”);

Reason :-
, because Gmail server doesn’t create folders in English always , i.e. if your profile is in French or Hindi your gmail folders names will be different.

Solution :-
Use the code below to get the available gmail folders for your account

Folder[] folder = store.getDefaultFolder().list(); // get the array folders in server
int i=0;
for( i=0;i<folder.length;i++)
System.out.println("Press "+i+" to read "+folder[i].getName()+" folder");
int choice=in.nextInt(); // getName() method returns the name of folder








Follow

Get every new post delivered to your Inbox.

Join 239 other followers