简体   繁体   中英

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

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM