【问题标题】:How to save MS Outlook attachments from specific sender and date using Python如何使用 Python 保存来自特定发件人和日期的 MS Outlook 附件
【发布时间】:2019-12-18 15:04:29
【问题描述】:

我对编码有点陌生,我正在尝试了解如何让 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

【问题讨论】:

  • Stack Overflow 面向特定的技术问题。因此,这似乎过于宽泛。 没有太多运气让它工作听起来可能更相关。
  • 感谢您的反馈。当我在 Python 中使用它时,我在其他表单上看到的代码似乎没有工作或做任何事情。下面是我尝试过的代码。 outlook=win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox=outlook.GetDefaultFolder(6) messages=inbox.Items 用于消息中的消息:附件 = message.attachments 用于附件中的附件:通过
  • 你能把它包含在你的帖子中吗(完整代码)?
  • 当然这段代码不起作用......它最后有一个pass,还是你故意隐瞒一些不必要的问题?

标签: python outlook attachment win32com


【解决方案1】:

你几乎明白了,给发件人的电子邮件地址添加过滤器

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

【讨论】:

  • 嗨@0m3r,我将如何根据主题过滤电子邮件?
【解决方案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)

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

【讨论】:

    猜你喜欢
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 2022-12-14
    • 2016-05-28
    • 2022-01-17
    • 1970-01-01
    • 2016-05-03
    相关资源
    最近更新 更多