Search code examples
pythonoutlookpywin32win32comoffice-automation

How to iterate through multiple outlook accounts using win32com.client


I have a requirement where in i need to handle 3 outlook accounts set in one profile. The scenario is similar for all 3 accounts, i just need to run through the scenario in 3 accounts one by one. Use case is as follows

Account_One has a folder in it : Folder_One. I will receive a mail in this folder with unique id in subject. I need to fetch data the To, Cc, Bcc and Comments data from an excel workbook. Update the mail with this info and move it to the drafts folder. Account_Two has a folder named Folder_Two and similarly Folder_Three for Account_Three.

I have handled the scenario for the single account. I am trying to iterate through a list of COM objects of account and folder name in a for loop to do this same process for different accounts but get a error that COM object is not iterable. Please suggest a way to overcome this scenario or how can I handle this.

Here is the code which I am trying

import win32com.client as client
From openpyxl import load_workbook

outlook = client.Dispatch(‘Outlook.Application’)
namespace = outlook.GetNameSpace(‘MAPI’)

accounts = [acc for acc in namespace.Folders if ‘[email protected]’ or ‘[email protected]’ == acc.Name

this gives me a list of accounts with type <class ‘win32com.client.CDispatch’>

for account in accounts:
    root = namespace.Folders[account]
    for folder in root.Folders:
        req_folder = root.Folders[folder]

this folder is currently a list of strings of the required folder names… you can suggest how can I get it as a COM Object as well…

Below code is just to manipulate the excel and mail.. which works fine if I use only one account.

I get an error on line ——> root = namespace.Folders[account] TypeError(“This object does not support enumeration”)

Please suggest a way to work this out


Solution

  • Replace the line

    root = namespace.Folders[account]
    

    with

    root = namespace.Folders.Item(account)