'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.

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")


Solution 1:[1]

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")

Solution 2:[2]

Firstly, it is Restrict, not Ryestrict.

Secondly, Restrict returns Items collection, not a single item. You need to iterate over the items in that collection. If you only expect a single item, use Find instead of Restrict.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dmitry Streblechenko