Reputation: 13
Am trying to get last 1000 emails i received in outlook. But the code only get Email from Main folder not from sub folders. Please assist
import win32com.client
import pandas as pd
import dateutil.parser
from datetime import datetime
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
# the inbox. You can change that number to reference
# any other folder
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
i=1
df = pd.DataFrame(columns=['Sender','Subject','DateTime'])
Today = datetime.now().strftime("%m/%d/%Y") # current date and time
while i<1000:
message=messages[i]
DT1=message.ReceivedTime
DT = DT1.strftime("%m/%d/%Y, %H:%M:%S")
a=message.SenderEmailAddress
if "-" in a:
a=a.split("-",1)[1]
b=message.subject
df = df.append({'Sender':a,'Subject':b,'DateTime':DT}, ignore_index=True)
i+=1
df.to_excel("C:/Users/abc/Downloads/Email.xlsx")
Upvotes: 0
Views: 2261
Reputation: 49453
To perform a search over multiple folders you need to use the AdvancedSearch
method of the Application
class. The key benefits of using the AdvancedSearch
method in Outlook are:
AdvancedSearch
method runs it automatically in the background.Restrict
and Find
/FindNext
methods can be applied to a particular Items
collection.IsInstantSearchEnabled
property of the Store
class).Read more about the AdvancedSearch
method and find samples in the Advanced search in Outlook programmatically: C#, VB.NET article.
The Restrict
or Find
/FindNext
methods of the Items
class allow getting items according to your conditions from a single folder only.
Upvotes: 0