如何使用 JavaMail 获取邮件帐户中可用文件夹的列表

2022-01-23 00:00:00 imap gmail java jakarta-mail

我正在使用 JavaMail API 连接到我的个人帐户.我的 Gmail 帐户中有我创建的文件夹(标签)列表 + 收件箱、草稿等默认文件夹.如何列出所有可用文件夹(默认文件夹和用户创建的文件夹)?

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)?

我可以使用以下 API 访问特定文件夹:Folder inbox = store.getFolder("Inbox");.是否有任何其他 API 可以获取邮件帐户中可用的文件夹列表?

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?

推荐答案

这是有效的代码.这将使您能够处理所有标签.要深入folder,您可以执行folder.list() 或使用store.getDefaultFolder().list("*") 以检索其他答案中建议的所有文件夹和子文件夹.

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

输出:

>>收件箱
>>个人
>>收据
>>旅游
>>工作
>>[邮箱]

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

<小时>

老答案

请注意这是不正确的,它在 this answer by dkarp

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

相关文章