3

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()
cyberbemon
  • 3,000
  • 11
  • 37
  • 62
  • 1
    I was having trouble getting the sender info using `message.Sender` in a previous project. Instead, I used `message.SenderName` to get their name and `message.SenderEmailAddress` for their email address. I'd also recommend using the `unidecode` package on the sender names since some people can have special characters in their name: `unidecode(message.SenderName)`. Adding a [doc](https://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.mailitem_properties.aspx) for MailItem properties. – Scratch'N'Purr May 03 '18 at 14:59

1 Answers1

1

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)

Dmitry Streblechenko
  • 62,942
  • 4
  • 53
  • 78