[英]How to save email from outlook using python
I am trying to save email from sub-folder using the below python script, I am trying to restrict with days=1
means I only need to save emails which are 1 day old.我正在尝试使用以下 python 脚本从子文件夹中保存电子邮件,我试图限制
days=1
意味着我只需要保存 1 天前的电子邮件。
from win32com.client import Dispatch
from datetime import date, timedelta
import datetime as dt
msg_location = r'C:\Users\rahul\Desktop\msg_files'
outlook = Dispatch("outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders['Email_snapper']
messages = inbox.Items
message = messages.GetFirst()
Body_content = message.Body
print(Body_content)
for msg in messages:
lastWeekDateTime = dt.datetime.now() - dt.timedelta(days=1)
lastWeekDateTime = lastWeekDateTime.strftime('%m/%d/%Y %H:%M %p')
message = messages.Ryestrict("[ReceivedTime] >= '" + lastWeekDateTime + "'")
#name = str(message)
message.SaveAs(msg+".msg")
Try setting your filter like the following尝试像下面这样设置你的过滤器
Example例子
import re
import win32com.client
import datetime as dt
import os
Outlook = win32com.client.Dispatch("Outlook.Application")
olNs = Outlook.GetNamespace("MAPI")
Inbox = olNs.GetDefaultFolder(6)
lastWeekDateTime = dt.datetime.now() - dt.timedelta(days=1)
lastWeekDateTime = lastWeekDateTime.strftime('%m/%d/%Y %H:%M %p')
print(lastWeekDateTime)
Filter = ("@SQL=" + chr(34) + "urn:schemas:httpmail:datereceived" +
chr(34) + " >= '" + lastWeekDateTime + "'")
Items = Inbox.Items.Restrict(Filter)
Items.Sort('[ReceivedTime]', False)
for Item in Items:
print(Item.Subject)
print(Item.ReceivedTime)
save_name = re.sub('[^A-Za-z0-9]+', '', str(Item.Subject)) + '.msg'
Item.SaveAs(os.getcwd() + '//' + save_name)
else:
print("No Item")
Firstly, it is Restrict
, not Ryestrict
.首先,它是
Restrict
,而不是Ryestrict
。
Secondly, Restrict
returns Items
collection, not a single item.其次,
Restrict
返回Items
集合,而不是单个项目。 You need to iterate over the items in that collection.您需要遍历该集合中的项目。 If you only expect a single item, use
Find
instead of Restrict
.如果您只期望一个项目,请使用
Find
而不是Restrict
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.