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

后端 未结 5 1401
暗喜
暗喜 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条回答
  •  猫巷女王i
    2020-12-07 21:07

    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", "@gmail.com", "");
        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();
    }
    

提交回复
热议问题