Python从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天左右访问我的收件箱,并从这个特定的电子邮件中下载这个特定的附件。

任何帮助都将不胜感激。

谢谢!

选择另一个驱动器或文件夹,例如,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类的Find/FindNextorRestrict`方法,该方法只允许获取与指定条件相对应的项。在以下文章中阅读更多关于这些方法的信息:

  • 如何:使用Find和FindNext方法从文件夹中检索Outlook邮件项目(C#、VB.NET(
  • 如何:使用Restrict方法从文件夹中检索Outlook邮件项目

默认情况下,用户没有对根驱动器(C:(的写访问权限。将其更改为类似'c:temp'的内容

最新更新