Jagadesh Jagadesh - 4 years ago 113
Java Question

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

I am using JavaMail API to connect to my personal account. I have list of folders (labels) in my Gmail account which I created + the default folders like Inbox, Drafts etc. How can I list all the available folders (the default and the user created)?

I can access the particular folder using this API:

Folder inbox = store.getFolder("Inbox");
. Is there any other API to get the list of folders available in a mail account?

Answer Source

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", "YOURMAILID@gmail.com", "UR_P@ZZWRD");

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


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


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

These should do:



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download