How to get the list of available folders in a mail account using JavaMail

Sergey is close, but by default JavaMail's list() does a LIST "" %, which gives you only top-level folders. GMail puts its system folders (All Mail, Drafts, Sent Mail, Spam, Starred, and Trash) under the non-selectable folder [Gmail], so you really need to do a LIST "" * instead. Otherwise, you'll just get back INBOX, [Gmail], and your labels.

Here's some sample code that connects to GMail, fetches the folder list, and prints out the name and message count for each non-\NoSelect folder (i.e. the ones that aren't just hierarchy placeholders, like [Gmail]):

Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
    Session session = Session.getDefaultInstance(props, null);
    javax.mail.Store store = session.getStore("imaps");
    store.connect("imap.gmail.com", "<username>@gmail.com", "<password>");
    javax.mail.Folder[] folders = store.getDefaultFolder().list("*");
    for (javax.mail.Folder folder : folders) {
        if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
            System.out.println(folder.getFullName() + ": " + folder.getMessageCount());
        }
    }
} catch (MessagingException e) {
    e.printStackTrace();
}

Here is the code that works. This will give you handle to all the Labels. To go deeper in a folder, you may perform folder.list() or you can use store.getDefaultFolder().list("*") to retrieve all the folders and sub-folders as suggested in the other answer.

Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "[email protected]", "UR_P@ZZWRD");
System.out.println(store);

Folder[] f = store.getDefaultFolder().list();
for(Folder fd:f)
    System.out.println(">> "+fd.getName());

Output:

>> INBOX
>> Personal
>> Receipts
>> Travel
>> Work
>> [Gmail]


OLD ANSWER

Please note this is not correct, it's rightly pointed in this answer by dkarp

These should do:

http://java.sun.com/products/javamail/javadocs/javax/mail/Store.html#getSharedNamespaces%28%29

http://java.sun.com/products/javamail/javadocs/javax/mail/Store.html#getUserNamespaces%28java.lang.String%29


You can access other folders like this

store.getFolder("[Gmail]/Sent Mail");
store.getFolder("[Gmail]/Drafts");

etc.