简体   繁体   English

如何使用 Python 从 outlook 下载 email 附件

[英]How to download email attachments from outlook using Python

I tried to use this script I found here .我尝试使用我在这里找到的这个脚本。 What I want to do is given either some subject line or email I will download and save the attachment.我想要做的是给出一些主题行或 email 我将下载并保存附件。

This is the code I used:这是我使用的代码:

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")

I am getting this error:我收到此错误:

  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)

The Outlook email is a work email and it is Microsoft Outlook 2010. Outlook email 是一个作品 email 它是微软 Z038E648F69B081222AD.

My question is how do I download and save attachments from Microsoft Outlook.我的问题是如何从 Microsoft Outlook 下载和保存附件。

Work with Items.Restrict Method (Outlook) to filter by subject line and attachment.使用Items.Restrict 方法 (Outlook)按主题行和附件进行过滤。 see 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 that DASL filters support includes equivalence, prefix, phrase, and substring matching. 使用 DASL 过滤器支持的字符串比较过滤项目包括等价、前缀、短语和 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 匹配。 Note that when you filter on the Subject property, prefixes such as "RE: " and "FW: " are ignored.请注意,当您对主题属性进行过滤时,会忽略诸如“RE:”和“FW:”之类的前缀。

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

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