【发布时间】:2019-09-13 13:32:02
【问题描述】:
我有一个脚本,可以将附件从 Outlook 复制到笔记本电脑上的文件夹中。到目前为止一切顺利,如果我只有一封带有已定义主题和附件的电子邮件,一切正常。今天我意识到,当我的收件箱中有一封新旧电子邮件具有相同的主题和附件名称时,会出现问题 - 看起来它随机接收旧邮件或新邮件。
问题:有没有办法告诉脚本要么总是接收最年轻的邮件,要么接收今天收到的邮件? 我尝试了在 stackoverlow 中找到的 GetLast() 和 GetFirst(),但不确定在哪里准确添加它(我的尝试导致错误)。有人有想法吗?
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")
【问题讨论】:
标签: python outlook outlook-filter