Search code examples
pythonoutlookpywin32win32com

Accessing Outlook using Python


I was accessing Outlook using python and got [COMObject unknown].

# https://www.codeforests.com/2020/06/04/python-to-read-email-from-outlook/

import win32com.client
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")

# print all outlook mail id
for account in mapi.Accounts:
    print(account.DeliveryStore.DisplayName)

# 6 means index refer to https://learn.microsoft.com/en-us/office/vba/api/outlook.oldefaultfolders
inbox = mapi.GetDefaultFolder(6)
messages = inbox.Items

print(messages)  # giving <COMObject <unknown>>

Last line gives

Unknown error.


Solution

  • inbox = mapi.GetDefaultFolder(6)
    messages = inbox.Items
    message = messages.GetFirst()
    while message:
        print(message.Subject)
        message = messages.GetNext()