简体   繁体   English

使用 Python 下载 Outlook 附件

[英]Downloading Outlook Attachments using Python

I'm new to Python coding and I've seen a couple questions on stack overflow about this topic, but can't seem to get the code to work.我是 Python 编码的新手,我看到了一些关于此主题的堆栈溢出问题,但似乎无法使代码正常工作。 I had some code that worked, but made the mistake of writing over that.我有一些有效的代码,但错误地写了它。 I'd like to download an attachment from my latest outlook email (I'll use a restrict statement to look for a specific email address at some point).我想从我最新的 Outlook 电子邮件中下载附件(我将在某个时候使用限制语句来查找特定的电子邮件地址)。 I tried this code and wondered why the error resulted (I have successfully downloaded an attachment from Outlook before, as previously mentioned).我尝试了这段代码并想知道为什么会导致错误(如前所述,我之前已经成功地从 Outlook 下载了一个附件)。

Code:

import win32com.client
import os

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
path=os.path.expanduser("C:\\Test")

inbox=outlook.GetDefaultFolder(6).Folders["Test"]
messages = inbox.Items
message = messages.GetLast()
#adjust the messages pulled by the python job to those from certain sender, then filter/interact with only those emails that
#are unread, then marks them read

for message in messages:
    if message.UnRead:
        attached_file = message.Attachments
        attachment = attached_file.Item(1)
        for attachment in attached_file:
            attachment.SaveAsFile(path)
            if message.UnRead:
                message.UnRead= False
            break

My Error:

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)
Other Code: (Executed with no error, but I didn't see the attachment save in the specified location)

import win32com.client
import os

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
path=os.path.expanduser("C:\\Test")

inbox=outlook.GetDefaultFolder(6).Folders["Test"]
messages = inbox.Items.Restrict("[SenderEmailAddress] = 'abc@1234.com'")
#adjust the messages pulled by the python job to those from certain sender, then filter/interact with only those emails that
#are unread, then marks them read

for message in messages:
    if message.UnRead:
        attached_file = message.Attachments
        attachment = attached_file.Item(1)
        for attachment in attached_file:
            attachment.SaveAsFile(os.path + str(attachment))
            if message.UnRead:
                message.UnRead= False
            break

Attachment.SaveAsFile take a fully qualified file name, not folder name. Attachment.SaveAsFile采用完全限定的文件名,而不是文件夹名。 Try尝试

attachment.SaveAsFile(os.path + "\\" + attachment.FileName)

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

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