Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 693
cyberbemon Avatar asked Apr 22 '26 15:04

cyberbemon


1 Answers

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)

like image 160
Dmitry Streblechenko Avatar answered Apr 24 '26 06:04

Dmitry Streblechenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!