Python 无法读取最新的 Outlook 附件,只能读取较旧的附件

Python can't read latest Outlook attachments, only older ones

情况:

我每天都会收到一封带附件的电子邮件,但我不想一直手动保存它,所以我制作了一个脚本来帮我下载它。

我在后台使用 Python 库 win32com 到 运行 Outlook:

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

脚本找到最新的带有附件的电子邮件并保存它。

问题:

它不保存最新的附件。它始终停留在同一封电子邮件中,就好像 Outlook 根本没有更新一样。唯一有效的情况是我删除我的 Outlook 配置文件并创建一个新配置文件。关于这种行为的原因有什么想法吗?

此致,

多由诺

代码:

# -*- coding: utf-8 -*-
import datetime

import pandas as pd
import win32com.client

path = "C:\some\path"
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

def getfoldernum():
    i = 1
    for x in outlook.Folders:
        if ('bob@example.com' == str(x)):
           print 'Found the Folder'
           return i
        else:
           i += 1

def main():
    foldernum = getfoldernum()

    inbox = outlook.Folders.Item(foldernum).Folders('Inbox')

    d = 0
    w = 0
    messages = inbox.Items
    for msg in messages:
        print msg.SentOn

        if msg.Attachments:
            attachments = msg.Attachments
            for attachment in attachments:
                if 'Attachment name' in str(attachment.FileName):
                    location = path + 'Archive\Daily\'+str(attachment.FileName)
                    attachment.SaveAsFile(location)
                    df = pd.read_excel(location)

                    if d == 0:
                        attachment.SaveAsFile(path+'filename.xlsx')
                        d = 1

                else:
                    print 'Attachment not found or wrong name'


if __name__ == '__main__':
    main()

您的脚本将作用于恰好位于集合 Items 中的第一个项目,并且您没有执行任何操作来指定应如何对该集合进行排序。因此,如果集合碰巧是按最近的项目排在第一位,那么您的代码恰好可以工作。您应该使用 Items.Sort 指定排序顺序。