cyberbemon
cyberbemon

Reputation: 3190

python win32com outlook, can't retrieve sender information.

I'm using win32com.client to interact with outlook. I've managed to retrieve the body and subject of the messages.

I based my code on the following post: Clearly documented reading of emails functionality with python win32com outlook

How ever I can only get the bodyand subjectanything else will either return <COMObject <unknown>> or the following error.

Traceback (most recent call last):
  File "C:/Users/xx/PycharmProjects/email_crawler/email_crawler.py", line 62, in <module>
    main()
  File "C:/Users/xx/PycharmProjects/email_crawler/email_crawler.py", line 56, in main
    retrieve_messages(outlook)
  File "C:/Users/xx/PycharmProjects/email_crawler/email_crawler.py", line 51, in retrieve_messages
    print(message.Sender)
  File "C:\Users\xx\PycharmProjects\email_crawler\venv\lib\site-packages\win32com\client\dynamic.py", line 527, in __getattr__
    raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: <unknown>.Sender

Here is my code.

def get_outlook():
        """
        :return: creates an instance of outlook and returns it.
        """
        outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
        return outlook


def retrieve_messages(outlook):
    """
    Retrieves messages from the inbox and returns a list.
    :param outlook: Instance of an outlook account
    :return:
    """
    inbox = outlook.GetDefaultFolder(6)
    messages = inbox.Items
    for message in messages:
        print(message.Sender)


def main():
    outlook = get_outlook()
    retrieve_messages(outlook)


if __name__ == "__main__":
main()

Upvotes: 3

Views: 9181

Answers (1)

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66215

Sender is indeed a COM object, not a string. It has properties like Name and Address. Keep in mind that not all items in your Inbox are MailItem objects - you can also have MeetingItem and ReportItem objects. If you only want MailItem objects, check that Class property = 43 (OlObjectClass.olMail)

Upvotes: 1

Related Questions