簡體   English   中英

如何使用 Python 從 outlook 下載 email 附件

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

我嘗試使用我在這里找到的這個腳本。 我想要做的是給出一些主題行或 email 我將下載並保存附件。

這是我使用的代碼:

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 email 是一個作品 email 它是微軟 Z038E648F69B081222AD.

我的問題是如何從 Microsoft Outlook 下載和保存附件。

使用Items.Restrict 方法 (Outlook)按主題行和附件進行過濾。 請參閱過濾項目

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

使用 DASL 過濾器支持的字符串比較過濾項目包括等價、前綴、短語和 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 匹配。 請注意,當您對主題屬性進行過濾時,會忽略諸如“RE:”和“FW:”之類的前綴。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM