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

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

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

我已经看到了一些有关使用win32com.client的文章,但运气不佳,无法与MS Outlook一起使用。我将在下面附加一些我尝试过的代码。感谢您的反馈!

导入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

bonaxi 回答:如何使用Python从特定发件人和日期保存MS Outlook附件

您差不多了,将过滤器添加到发件人电子邮件地址

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 具体来说,其属性

本文链接:https://www.f2er.com/2898163.html

大家都在问