【问题标题】:How to download email attachments from outlook using Python如何使用 Python 从 Outlook 下载电子邮件附件
【发布时间】:2020-07-20 00:38:06
【问题描述】:

我尝试使用我找到的这个脚本here。我想要做的是给出一些主题行或电子邮件,我将下载并保存附件。

这是我使用的代码:

import datetime
import os
import win32com.client


path = os.path.expanduser("//cottonwood//users///MyDocuments//Projects//outlook crawler")

today = datetime.date.today()

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) 
messages = inbox.Items

def saveattachemnts(subject):
    for message in messages:
        if message.Subject == subject and message.Unread or message.Senton.date() == today:
            # body_content = message.body
            attachments = message.Attachments
            attachment = attachments.Item(1)
            for attachment in message.Attachments:
                attachment.SaveAsFile(os.path.join(path, str(attachment)))
                if message.Subject == subject and message.Unread:
                    message.Unread = False
                break

saveattachemnts("Snarf")

我收到此错误:

  File "<COMObject <unknown>>", line 2, in Item
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Array index out of bounds.', None, 0, -2147352567), None)

Outlook 电子邮件是工作电子邮件,它是 Microsoft Outlook 2010。

我的问题是如何从 Microsoft Outlook 下载和保存附件。

【问题讨论】:

标签: python email outlook email-attachments win32com


【解决方案1】:

与 Items.Restrict Method (Outlook) 合作,按主题行和附件进行过滤。见Filtering Items

import win32com.client

Outlook = win32com.client.Dispatch("Outlook.Application")
olNs = Outlook.GetNamespace("MAPI")
Inbox = olNs.GetDefaultFolder(6)

Filter = ("@SQL=" + chr(34) + "urn:schemas:httpmail:subject" +
                    chr(34) + " Like 'Snarf' AND " +
                    chr(34) + "urn:schemas:httpmail:hasattachment" +
                    chr(34) + "=1")

Items = Inbox.Items.Restrict(Filter)
for Item in Items:
    for attachment in Item.Attachments:
        print(attachment.FileName)
        attachment.SaveAsFile(r"C:\\subfolder\\" + attachment.FileName")

Filtering Items Using a String Comparison DASL 过滤器支持包括等价、前缀、短语和子字符串匹配。请注意,当您对主题属性进行过滤时,会忽略诸如“RE:”和“FW:”之类的前缀。

【讨论】:

  • 这似乎可行,但我收到此错误:(4096,'Microsoft Outlook',“无法保存附件。您没有执行此操作的适当权限。”,无,0 , -2147024891), 无)。
  • 我猜我需要获得许可什么的?
  • 确保您的路径带有文件名、c:\filename.pdf 或其他任何内容,我想也许可以尝试使用不同的文件夹,而不仅仅是 c:\ drive- 示例 c:\folder\filename.pdf @justanewb
  • 我明白了:^ SyntaxError: EOL while scanning string literal
  • 好的,试试这个attachment.SaveAsFile("C:\\subfolder\\" + attachment.FileName) @justanewb
猜你喜欢
  • 2019-06-18
  • 2018-01-16
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
  • 2014-05-25
相关资源
最近更新 更多