Search code examples
pythonoutlookpywin32win32comoffice-automation

How to get primary outlook account using python


I would like to get the primary outlook email address using python ,my code likes below:

import win32com.client as client
outlook=client.gencache.EnsureDispatch('Outlook.Application')
accounts = outlook.Session.Accounts
print(accounts)
for i in accounts:
    print(i.SmtpAddress)

the error :

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_7276/1677428506.py in <module>
      3 accounts = outlook.Session.Accounts
      4 print(accounts)
----> 5 for i in accounts:
      6     print(i.SmtpAddress)

TypeError: 'Accounts' object is not iterable

output expected: mail format (sth like [email protected])


Solution

  • I have found a solution for my case already , the code below could work fine:

    import win32com.client as win32
    outlook_app = win32.gencache.EnsureDispatch('Outlook.Application')
    ons = outlook_app.GetNamespace("MAPI")
    count1 = outlook_app.Session.Accounts.Count
    print(count1)
    for i in range(1,count1+1):
    
        if ons.Accounts.Item(i).DisplayName.lower().find("thakral") != -1:
            print(ons.Accounts.Item(i).DisplayName)
            print("TRUE")