【问题标题】:Python Saving Attachments from OutlookPython 从 Outlook 保存附件
【发布时间】:2021-05-24 13:40:17
【问题描述】:

我正在尝试自动化一些 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 天访问一次我的收件箱或所以并从这个特定的电子邮件下载这个特定的附件。

任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: python outlook email-attachments pywin32 win32com


    【解决方案1】:

    选择另一个驱动器或文件夹,例如,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` 方法,该方法只允许获取与指定条件相对应的项目。在以下文章中详细了解这些方法:

    【讨论】:

      【解决方案2】:

      默认情况下,用户没有对根驱动器 (C:) 的写入权限。 将其更改为 'c:\temp\'

      【讨论】:

      • 代码(很可能)不会尝试写入根目录。它尝试写入C:some_file(注意缺少的反斜杠)。这是有效的,尽管unusual syntax 用于:写入驱动器C 的当前工作目录中的some_file。这仍然不是有意的或错误的。
      • C:some_file 在 C:\ 驱动器的根文件夹中。如果没有海拔,你就无法做到这一点。
      • 不,不是。此特定语法涉及当前工作目录。另一方面,C:\some_file 在根目录中。
      • 'C:'.Format(someValue) 将在 Python 中生成 'C:' ,不是吗? save_path 应该类似于`'c:\SomeExistingFolder\{0}'`
      • 不确定,你想说什么。标记当然会妨碍。
      猜你喜欢
      • 2016-05-28
      • 2022-01-17
      • 2022-12-14
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      相关资源
      最近更新 更多