2

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")
4
  • i used it to save the email Commented Mar 1, 2022 at 16:52
  • File "C:\Users\RahulPycharmProjects\pythonProject3\Testing email.py", line 24, in <module> message.SaveAs(msg+".msg") File "C:\Users\Rahull\AppData\Local\Programs\Python\Python39\lib\site-packages\win32com\client\dynamic.py", line 511, in getattr raise AttributeError("%s.%s" % (self._username_, attr)) AttributeError: Restrict.SaveAs Commented Mar 1, 2022 at 17:02
  • i would like to name it with subject line + the date it is received on Commented Mar 1, 2022 at 17:03
  • i just posted in comments section Commented Mar 1, 2022 at 17:11

2 Answers 2

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")
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for this 0m3r, what's the use of @sql here ?
and in case i need to add a subfolder, can i use something like inbox = outlook.GetDefaultFolder(6).Folders['sub_folder_name']
Also, is there a way to save those mails to a local folder ? like all the emails present in sub folder with filter time as today
@RahulVaidya, answer updated to save mails
0

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.

7 Comments

Hi Dmitry, thanks for the suggestions, now it is failing on the last line (message.SaveAs(msg+".msg")
i am trying to save all the emails from sub-folder with subjectline + received time
SaveAs takes fully qualified file name. e.g. c:\temp\mymessage.msg. Secondly, msg is an object, not a string, so you end up with the default string property, which is Subject. And subject can contain invalid (for a file name) characters (e.g. :). You need to clean up the file name first.
can you please help me with the correct line of code ?
What exactly are you having problems with?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.