簡體   English   中英

Python 從 Outlook 保存附件

[英]Python Saving Attachments from Outlook

我正在嘗試自動化一些 python 代碼,該代碼將自動保存某些具有特定標題的電子郵件中的一些附件。

以下是我目前擁有的:

import win32com.client as client

outlook = client.Dispatch('Outlook.Application')
namespace = outlook.GetNameSpace('MAPI')
inbox = namespace.GetDefaultFolder(6)
target_subject = 'Testing attachment'
mail_items = [item for item in inbox.Items if item.Class == 43]
filtered = [item for item in mail_items if item.Subject == target_subject]


if len(filtered) != 0:
    target_email = filtered[0]
    

if target_email.Attachments.Count > 0:
    attachments = target_email.Attachments    
    

save_path = 'C:'

for file in attachments:
    file.SaveAsFile(save_path.format(file.FileName))  

但是我似乎遇到了權限錯誤?

com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', "Cannot save the attachment. You don't have appropriate permission to perform this operation.", None, 0, -2147024891), None)

不知道如何解決這個問題,我是管理員等。

我還想知道實際在線部署並運行它所需的更改是什么,即我沒有傳遞任何憑據,因為它是本地的,如果獨立運行我希望它每 7 天左右訪問我的收件箱並下載此特定 email 的特定附件。

任何幫助將不勝感激。

謝謝!

選擇另一個驅動器或文件夾,例如, My Documents不需要管理員權限即可寫入。 否則,如果您想向系統驅動器 (C:) 寫入任何內容,則必須以管理員權限運行 Outlook。

我還注意到以下代碼行:

mail_items = [item for item in inbox.Items if item.Class == 43]
filtered = [item for item in mail_items if item.Subject == target_subject]

遍歷文件夾中的所有項目並不是一個好主意,而且,你這樣做了兩次!

我建議使用 Items class 的Find /FindNext or Restrict` 方法,這些方法只允許獲取與指定條件相對應的項目。 在以下文章中閱讀有關這些方法的更多信息:

默認情況下,用戶沒有對根驅動器 (C:) 的寫入權限。 將其更改為'c:\temp\'

暫無
暫無

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

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