使用python将今天收到的电子邮件中的附件复制到文件夹中 [英] Copy attachment from todays received email to folder with python
问题描述
我有一个脚本,可以将附件从Outlook复制到笔记本电脑上的文件夹中.到目前为止,如果我只有一封带有定义的主题"和附件"的电子邮件,那么一切都很好.如今,我意识到,收件箱中有一封新邮件和一封较旧的电子邮件,并且主题和附件名称相同时,就会出现问题-好像它随机接收旧邮件或新邮件一样.
I have a script which copies an attachment from outlook to a folder on my laptop. So far so good, if I only have one email with the defined Subject and Attachment everything works fine. Today I realized that there's a problem when I have a newer and an older email with the same subject and attachment name in my inbox - it looks like it randomly takes the old or the new one.
问题:是否可以告诉脚本始终接收最年轻的邮件还是接收今天收到的邮件? 我尝试了在stackoverlow中找到的GetLast()和GetFirst(),但不确定确切在哪里添加它(我的尝试导致错误).有人有主意吗?
Question: Is there a way to tell the script to either always take the youngest mail or take the mail received today? I tried around with GetLast() and GetFirst(), what I found in stackoverlow, but wasn't sure where to add it exactly (my trys resulted in errors). Anyone having an idea?
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")
推荐答案
GetLast
和GetFirst
是链接到inbox.Items
all_inbox = inbox.Items
all_inbox.Sort('[ReceivedTime]', True)
first = all_inbox.GetFirst()
last = all_inbox.GetLast()
如@Dmitry Streblechenko所述,您需要先按ReceivedTime对收件箱进行排序.
As stated by @Dmitry Streblechenko you need to sort by ReceivedTime first the inbox.Items
这篇关于使用python将今天收到的电子邮件中的附件复制到文件夹中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!