繁体   English   中英

如何使用 Python 保存来自特定发件人和日期的 MS Outlook 附件

[英]How to save MS Outlook attachments from specific sender and date using Python

我对编码有点陌生,我试图了解如何让 Python 保存来自特定发件人的 MS Outlook 附件。 我目前每天都会收到来自同一个人的关于我需要保存到特定文件夹的数据的相同电子邮件。 以下是我试图满足的要求:

  1. 我想打开 MS Outlook 并搜索特定的发件人
  2. 我想确保我从特定发件人处打开的电子邮件是最新日期
  3. 我想将此发件人的所有附加文件保存到我桌面上的特定文件夹中

我看过一些关于使用 win32com.client 的帖子,但没有太多运气让它与 MS Outlook 一起工作。 我将附上我在下面尝试过的一些代码。 我感谢任何反馈!

import win32com.client
outlook=win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox=outlook.GetDefaultFolder(6)
messages=inbox.Items
for message in messages:
    attachments = message.attachments
    for attachment in attachments:
        pass

你差不多明白了,为发件人电子邮件地址添加过滤器

import win32com.client

Outlook = win32com.client.Dispatch("Outlook.Application")
olNs = Outlook.GetNamespace("MAPI")
Inbox = olNs.GetDefaultFolder(6)

Filter = "[SenderEmailAddress] = '0m3r@email.com'"

Items = Inbox.Items.Restrict(Filter)
Item = Items.GetFirst()

for attachment in Item.Attachments:
    print(attachment.FileName)
    attachment.SaveAsFile(r"C:\path\to\my\folder\Attachment.xlsx")

Windows 上的 Python 3.8

def saveAttachments(email:object):
        for attachedFile in email.Attachments: #iterate over the attachments
                try:
                        filename = attachedFile.FileName
                        attachedFile.SaveAsFile("C:\\EmailAttachmentDump\\"+filename) #Filepath must exist already
                except Exception as e:
                        print(e)

for mailItem in inbox.Items:
        #Here you just need to bould your own conditions
        if mailItem.Sender == "x" or mailItem.SenderName == "y":
               saveAttachments(mailItem)

您可以根据自己的喜好更改实际情况。 我建议参考 Outlook MailItem 对象的对象模型: https : //docs.microsoft.com/en-gb/office/vba/api/outlook.mailitem特别是它的属性

暂无
暂无

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

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