用python将附件从今天收到的电子邮件复制到文件夹

2024-05-21 07:45:46 发布

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

我有一个脚本,可以将outlook中的附件复制到笔记本电脑上的文件夹中。到目前为止还不错,如果我只有一个电子邮件与定义的主题和附件一切正常。今天我意识到有一个问题,当我有一个新的和旧的电子邮件与相同的主题和附件名称在我的收件箱-它看起来像是随机采取旧的或新的。你知道吗

问:有没有一种方法可以告诉脚本,要么总是接受最年轻的邮件,要么接受今天收到的邮件? 我试过使用GetLast()和GetFirst(),我在stackoverlow中找到了这两个选项,但不确定到底要添加到哪里(我的尝试导致了错误)。有人有主意吗?你知道吗

from win32com.client import Dispatch
import datetime as date

outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
val_date = date.date.today()

sub_today = 'Email Subject'
att_today = 'Attachment.zip'

for msg in all_inbox:
    if msg.Subject == sub_today:
        break

for att in msg.Attachments:
    if att.FileName == att_today:
        break


att.SaveAsFile(r'C:\path\to\my\folder\Attachment.zip')

编辑(解决方案):

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

Filter = ("@SQL=" + chr(34) + "urn:schemas:httpmail:subject" +
          chr(34) + " Like 'ATTACHMENTNAMEHERE' AND " +
          chr(34) + "urn:schemas:httpmail:hasattachment" +
          chr(34) + "=1")


Items = Inbox.Items.Restrict(Filter)
Items.Sort('[ReceivedTime]', False)
Item = Items.GetLast()

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

Tags: importclient附件attachmenttodaydateitemszip
3条回答

GetLastGetFirst是链接到inbox.Items的方法

all_inbox = inbox.Items
all_inbox.Sort('[ReceivedTime]', True)
first = all_inbox.GetFirst()
last = all_inbox.GetLast()

编辑:正如@Dmitry Streblechenko所说的,您首先需要按接收时间排序收件箱。项目你知道吗

首先,千万不要遍历文件夹中的所有项目,这就是ItemsFind/FindNextItems.Restrict的用途。在您的特定情况下,可以调用all_inbox.Find('[Subject] = ''somevalue'' ')来查找具有给定主题的消息。你知道吗

其次,您需要首先对Items集合进行排序—例如,调用all_inbox.Sort('[ReceivedTime]', true)按接收日期对消息进行排序。之后,您可以调用Items.Find来查找最新的消息。你知道吗

接下来呢。。。


import win32com.client

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

Filter = ("@SQL=" + chr(34) + "urn:schemas:httpmail:subject" +
          chr(34) + " Like 'Email Subject' AND " +
          chr(34) + "urn:schemas:httpmail:hasattachment" +
          chr(34) + "=1")

Items = Inbox.Items.Restrict(Filter)
Items.Sort('[ReceivedTime]', False)
Item = Items.GetLast()

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

Items.GetLast method (Outlook)

Items.Restrict method (Outlook)

相关问题 更多 >