Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IMAP List extension JAVA

I'm building a tool that need access to mail specific folders (e.g. '[Gmail]/Trash', '[Gmail]/Sent'). It seems that the names are localized with respect to the user localization settings, so '[Gmail]/Trash' show as '[Gmail]/Papelera' to Spanish users for example.

I read about XLIST command but now is deprecated in favor of the IMAP LIST Extension (https://developers.google.com/gmail/imap_extensions#special-use_extension_of_the_list_command).

I tried to do it that way javax.mail.Folder.list("\Trash") but nothing is returned.

How can I use the IMAP List extension in JAVA?

PS: Using several email providers, not just Gmail.

like image 253
Ydrojen Avatar asked Jan 29 '14 10:01

Ydrojen


1 Answers

As Bill Shannon said, You can use Gmail attributes to get special folders like Trash. But this will work only with Gmail.

javax.mail.Folder[] folders = store.getDefaultFolder().list("*");

If you print this, it should look like the following as per Gmail

a004 LIST "" "*"
* LIST (\HasNoChildren) "/" "INBOX"
* LIST (\Noselect \HasChildren) "/" "[Gmail]"
* LIST (\HasNoChildren \All) "/" "[Gmail]/All Mail"
* LIST (\HasNoChildren \Drafts) "/" "[Gmail]/Drafts"
* LIST (\HasNoChildren \Important) "/" "[Gmail]/Important"
* LIST (\HasNoChildren \Sent) "/" "[Gmail]/Sent Mail"
* LIST (\HasNoChildren \Junk) "/" "[Gmail]/Spam"
* LIST (\HasNoChildren \Flagged) "/" "[Gmail]/Starred"
* LIST (\HasNoChildren \Trash) "/" "[Gmail]/Trash"
a004 OK Success

Once you have the folders with you, you can iterate for the attribute you are looking for.

For [Gmail]/All Mail, mailFolder = "\\All". similarly for [Gmail]/Trash it will be mailFolder = "\\Trash"

private static IMAPFolder getLocalisedFolder(IMAPStore store, String mailFolder) throws MessagingException {
 Folder[] folders = store.getDefaultFolder().list("*");
 for (Folder folder : folders) {
   IMAPFolder imapFolder = (IMAPFolder) folder;
   for (String attribute : imapFolder.getAttributes()) {
     if (mailFolder.equals(attribute)) {
       return imapFolder;
     }
   }
 }
 return null;
}
like image 198
Sridhar Avatar answered Oct 09 '22 02:10

Sridhar