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

后端 未结 5 1402
暗喜
暗喜 2020-12-07 20:23

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.

5条回答
  •  情书的邮戳
    2020-12-07 21:01

    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");
    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

提交回复
热议问题