簡體   English   中英

使用win32com模塊從Outlook下載附件

[英]Download attachments from Outlook using win32com module

我想從 outlook 下載多個附件。 我現在有這段代碼,但有這個問題。

在這張照片中:

在此處輸入圖像描述

你看到attachment變量有問題。

Error: pywintypes.com_error: (-2147352567, 'Exception occurred.', 
  (4096, 'Microsoft Outlook', 'Array index out of bounds.', None, 0, -2147352567), None)

代碼:

import datetime
import os
import win32com.client


path = ("C:/Users/greencolor/Desktop/Autoreport/")
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

download = saveattachemnts('PB report - next steps')

您假設郵件有附件並且無條件地訪問第一個附件。 您需要檢查attachments.Count > 0

您不能將attachment分配給attachments.Item(1)然后在 for 循環中使用它來迭代message.Attachments

嘗試示例

import datetime
import os
import win32com.client

path = r"C:/Users/greencolor/Desktop/Autoreport/"
today = datetime.date.today()

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


def save_attachments(subject):
    for message in messages:
        if message.Subject == subject and message.Unread or message.Senton.date() == today:
            for attachment in message.Attachments:
                print(attachment.FileName)
                attachment.SaveAsFile(os.path.join(path, str(attachment)))


if __name__ == "__main__":
    save_attachments('PB report - next steps')

暫無
暫無

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

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