Home > Back-end >  How to save email from outlook using python
How to save email from outlook using python

Time:03-03

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

CodePudding user response:

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.

CodePudding user response:

Try setting your filter like the following

Example

import win32com.client
import datetime as dt

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)
else:
    print("No Item")
  • Related