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

2024-06-28 20:30:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编码有点陌生,我正在尝试理解如何让Python保存特定发件人的msoutlook附件。我现在每天都会收到同一个人发来的关于我需要保存到特定文件夹的数据的邮件。以下是我努力满足的要求:

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

我看过一些关于使用win32的帖子com客户端但在与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

Tags: in文件夹clientmessage编码for附件attachments
2条回答
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)

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

你就快成功了,给发件人的电子邮件地址添加过滤器

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

相关问题 更多 >