简体   繁体   中英

Get Email list from Outlook using Python

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

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:

  • The search is performed in another thread. You don't need to run another thread manually since the AdvancedSearch method runs it automatically in the background.
  • Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, ie beyond the scope of a certain folder. The Restrict and Find / FindNext methods can be applied to a particular Items collection.
  • Full support for DASL queries (custom properties can be used for searching too). You can read more about this in the Filtering article in MSDN. To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the IsInstantSearchEnabled property of the Store class).
  • You can stop the search process at any moment using the Stop method of the Search 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.

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