0
votes

My goal is to search an entire Outlook email box in order to find/extract emails with a specific subject.

My code is the following:

import win32com.client
import os
import re

path = 'C:/working path'
os.chdir(path)

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

user = outlook.Application.Session.CurrentUser.AddressEntry.GetExchangeUser().PrimarySmtpAddress

inbox = outlook.Folders[user].Folders["Inbox"]


for i in inbox.Folders:
    subfolders = i.Items
    print(i.name)
    for message in subfolders:
        if message.subject.startswith('Report on X'):
            print(message.subject)
            title = str(message.subject)
            message.SaveAs(os.getcwd() + '//' + title + '.msg')
        else:
            print('skipped')

My problem is that I have messages in different folder levels. In other words, I have folders, subfolders, subsubfolders, ... and so on.

With the code above I can only access the Folder "Inbox" and only its subfolders. So if the email I'm searching for is in a subsubfolder I can't find it.

Is there a way to search the entire Outlook email box without specifiying the names of the folders, subfolders, etc. ?

1

1 Answers

0
votes

I recommend that you take a look at the .Folders field. Right now you are only accessing the "Inbox" value of that field, but I'd assume that it has access to every other folder. For example:

print(inbox = outlook.Folders[user].Folders)

If this displays an array of all the folders, then you can simply loop through each folder in that array.

for i in outlook.Folders[user].Folders.Folders:
    subfolders = i.Items
    print(i.name)
    for message in subfolders:
        if message.subject.startswith('Report on X'):
            print(message.subject)
            title = str(message.subject)
            message.SaveAs(os.getcwd() + '//' + title + '.msg')
        else:
            print('skipped')