简体   繁体   English

Python 从 Outlook 保存附件

[英]Python Saving Attachments from Outlook

I am trying to automate some python code that will automatically save some attachments from certain emails with a specific title.我正在尝试自动化一些 python 代码,该代码将自动保存某些具有特定标题的电子邮件中的一些附件。

Below is what I currently have:以下是我目前拥有的:

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

However I seem to be getting an error with permissions?但是我似乎遇到了权限错误?

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)

Not sure how to work around this, I am the Admin etc.不知道如何解决这个问题,我是管理员等。

I am also wondering what would be the changes required to actually deploy this online and have it running, ie I am not passing any credentials as it's local, if operating stand alone I would like it to access my inbox every 7 days or so and download this specific attachments from this specific email.我还想知道实际在线部署并运行它所需的更改是什么,即我没有传递任何凭据,因为它是本地的,如果独立运行我希望它每 7 天左右访问我的收件箱并下载此特定 email 的特定附件。

Any help will be greatly appreciated.任何帮助将不胜感激。

Thanks!谢谢!

Choose another drive or folder, for example, My Documents doesn't require admin privileges for writing.选择另一个驱动器或文件夹,例如, My Documents不需要管理员权限即可写入。 Otherwise, you will have to run Outlook with admin privileges if you want to write anything to the system drive (C:).否则,如果您想向系统驱动器 (C:) 写入任何内容,则必须以管理员权限运行 Outlook。

Also I've noticed the following lines of code:我还注意到以下代码行:

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

Iterating over all items in the folder is not really a good idea, moreover, you are doing that twice!遍历文件夹中的所有项目并不是一个好主意,而且,你这样做了两次!

I'd recommend using the Find /FindNext or Restrict` methods of the Items class that allow getting only items that correspond to the specified condition.我建议使用 Items class 的Find /FindNext or Restrict` 方法,这些方法只允许获取与指定条件相对应的项目。 Read more about these methods in the following articles:在以下文章中阅读有关这些方法的更多信息:

Users by default do not have write access to the root drive (C:).默认情况下,用户没有对根驱动器 (C:) 的写入权限。 Change it to something like 'c:\temp\'将其更改为'c:\temp\'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM