繁体   English   中英

在 for 循环中遍历字典中的列表

[英]Iterating through a list within dictionary in a for loop

我正在尝试将来自 outlook 的所有邮件存储在数据库中。 为此,我需要遍历 outlook 中的每个文件夹。为此,我正在使用 win32com.client。 我创建了一个字典,将邮箱的每个名称作为键,将所有文件夹作为具有值的列表。

postbox_and_folders = {} 
folder_of_postbox = [] 
for postbox in postboxes:
    for idx, folder in enumerate(mapi.Folders(postbox).Folders):
        folder_of_postbox.append(str(folder))
        postbox_and_folders[postbox] = folder_of_postbox
        if str(folder) == 'Archive':
            folder_of_postbox = [] 
print(postbox_and_folders)

output 看起来像这样:

{'@VPC': ['Calendar', 'Contacts', 'Conversation Action Settings', 'Conversation History', 'Deleted Items', 'Drafts', 'Einstellungen für QuickSteps', 'ExternalContacts', 'Files', 'Inbox', 'Journal', 'Junk Email', 'Notes', 'Outbox', 'PersonMetadata', 'Sent Items', 'Social Activity Notifications', 'Sync Issues', 'Tasks', 'Yammer Root', 'Archive'], '@FCC': ['Calendar', 'Contacts', 'Conversation Action Settings', 'Conversation History', ...] which is exactly how it should look.

现在我的目标是 go 通过每个邮箱及其各自的文件夹将邮件正文存储在数据库中。

我知道我必须使用 mapi.Folders 但无法使其与这本词典一起使用。 如何使用这本字典遍历每个文件夹?

我只需要将字典放在这个function中,我觉得我已经很接近了。

for key, value in postbox_and_folders.items():
messages = mapi.Folders(str(key)).Folders(value[i]).Items
for message in list(messages)[:10]:
    print(message.Body)

您需要递归地遍历所有子文件夹。 例如,C# 中的原始草图为 Outlook object model 对于所有类型的编程语言都是通用的:

private void EnumerateFoldersInDefaultStore()
{
    Outlook.Folder root =
        Application.Session.
        DefaultStore.GetRootFolder() as Outlook.Folder;
    EnumerateFolders(root);
}

// Uses recursion to enumerate Outlook subfolders.
private void EnumerateFolders(Outlook.Folder folder)
{
    Outlook.Folders childFolders =
        folder.Folders;
    if (childFolders.Count > 0)
    {
        foreach (Outlook.Folder childFolder in childFolders)
        {
            // Write the folder path.
            Debug.WriteLine(childFolder.FolderPath);
            // Call EnumerateFolders using childFolder.
            EnumerateFolders(childFolder);
        }
    }
}             

您可能会发现一个类似的问题,循环 outlook 文件夹和子文件夹线程中的所有电子邮件很有帮助。

如果要存储文件夹名称,您也可以(或改为)存储文件夹条目 ID ( MAPIFolder.EntryID )。 如果您知道文件夹条目 ID,则可以随时使用Application.Session.GetFolderFromID打开它。

但是请记住,您只处理一个级别的文件夹,并且您确实需要递归地处理它们 - 创建一个将MAPIFolder作为参数的 function。 然后 function 可以枚举子文件夹( MAPIFolder.Folders集合)并为每个子文件夹调用自身。

您错过了循环遍历每个邮箱中的文件夹的循环,试试这个,

for key, value in postbox_and_folders.items():
    for i in value:    
        messages = mapi.Folders(str(key)).Folders(value[i]).Items
        for message in list(messages)[:10]:
            print(message.Body)

希望这有效!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM