阅读邮件时无附件(无法保存附件)

Chr*_*lor 3 python email-attachments microsoft-graph-api

我正在使用 python 和 O365 库访问 MS O365 邮件帐户,但无法访问/保存邮件的文件附件

我已经使用普通的 IMAP 等完成了这项工作,但是现在,因为我们必须使用 oauth2 和所有这些 - 我必须通过 MS-Graph 或其他方式访问邮箱。

我选择了 python-O365 库,它允许我做我需要的事情。

我可以获取文件夹和消息(名称、正文等),但是当我尝试使用 message.attachments 方法时 - 我收到消息,附件数量未知。

我知道我自己发送的这条消息有两个 XLSX 附件,而且我可以验证我正在阅读正确的消息,因为我可以阅读它的正文。

我搜索了保存附件的示例(使用 O365 库),但它们没有解决问题(它们遍历附件集合 - 但我没有任何附件)。

我已经读到附件与消息分开存储,并且需要单独获取这些附件,但不知何故这似乎是错误的?

下面的代码说明了这个问题......

for message in inbox.get_messages(5):
    print(message.subject)
    if message.subject == 'test':
        print('here')
        for att in message.attachments:
            print('also here')
            print(att.attachment_name)
            print(att.attachment_type)
            att.save()
Run Code Online (Sandbox Code Playgroud)

从上面我得到了打印的文本“here” - 所以我知道正在使用正确的消息。我没有收到我应该收到的文本“也在这里”,因为消息中有两个文件。

那么 - 有什么想法可以保存我的附件吗?

Chr*_*lor 5

它只是显示了一点时间,清晨和一些好咖啡可以带来什么......

我找到了答案。它被埋在 github 上 O365 库的问题跟踪器中。

以下代码正常工作:

for message in inbox.get_messages(limit=10, download_attachments=True):
    if message.subject == 'test with file':
        print('here')
        if message.has_attachments:
            print('also here')
            print(message.attachments)
            for att in message.attachments:
                print(att)
                att.save()
Run Code Online (Sandbox Code Playgroud)

将其与原始代码进行比较,您将看到我需要将 get_messages 指示为 download_attachments=True 并且访问附件的机制也发生了变化。

无论如何 - 它现在正在工作:)

  • 这个故事有一点更新... Outlook 似乎可以在文件名中使用非法字符。如果您使用 att.save() 方法,O365 API 将不会保存这些文件并返回 False。我所做的(也许不是最好的方法 - 但有效 - 是去掉非法字符,然后执行以下操作: att.save(location=mailDir, custom_name=fixFileName(att.name)) 该文档没有提到这两个变量你可以传入,但如果你查看源代码 - 你可以看到它们。 (3认同)