首页 > 解决方案 > 使用 Python 通过子文件夹中的消息保存 Outlook 中的附件

问题描述

我想使用以下结构从 Outlook 中保存 Outlook 附件:

附加(在桌面上)--> 文件夹(Outlook 中子文件夹的名称)--> 文件夹(单个邮件)--> 邮件中的附件

我遇到了一个问题,由于某种原因,子文件夹中的所有附件都保存到每个邮件文件夹中,而不仅仅是它们所属的邮件文件夹。

对不起,如果我的代码是多余的,我刚刚开始学习!

import win32com.client as client
import os

outlook = client.Dispatch('Outlook.Application').GetNamespace('MAPI')

path = 'C:\\Users\\XXXXX\\Desktop\\Attach'
os.chdir(path)

inbox = outlook.GetDefaultFolder(6)
inboxfolders = inbox.Folders
inbxcount = inboxfolders.Count

folderlist = []
for x in range(1, inbxcount + 1):
    subfolder = inboxfolders[f'{x}']
    strsub = str(subfolder)
    if 'PRs' in strsub:
        folderlist.append(strsub)
for i in folderlist:
    newfolder = i
    os.makedirs(newfolder)
    sub = inboxfolders[f'{i}']
    messages = sub.Items
    msgcount = messages.Count
    newpath = f'{path}\\{newfolder}'
    for y in range(1, msgcount + 1):
        msgfolder = f'PR{y}'
        os.chdir(newpath)
        os.makedirs(msgfolder)
        path3 = f'{newpath}\\PR{y}'
        for msg in range(1, msgcount + 1):
            message = messages.Item(msg)
            attachments = message.Attachments
            attchcount = attachments.Count
            for attch in range(1, attchcount + 1):
                attachment = attachments.Item(attch)
                sattachment = str(attachment)
                if 'image' not in sattachment:
                    attachment.SaveAsFile(os.path.join(path3, sattachment))
                    os.chdir(path)

标签: pythonoutlook

解决方案


解决方案是删除对单个消息进行迭代的第二个 for 循环。通过这样做,它消除了额外的附件。


推荐阅读