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("", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("", "<username>", "password");

Folder inbox = store.getFolder("Inbox");;
Message messages[] = inbox.getMessages();
for(Message message:messages) {
} catch (NoSuchProviderException e) {
} catch (MessagingException e) {



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


Get every new post delivered to your Inbox.

Join 239 other followers