python win32com outlook,无法检索发件人信息。

时间:2018-05-03 14:49:28

标签: python outlook pywin32

我正在使用win32com.client与Outlook进行互动。我设法检索了消息的正文和主题。

我的代码基于以下帖子:Clearly documented reading of emails functionality with python win32com outlook

我怎么才能得到bodysubject其他任何内容都会返回<COMObject <unknown>>或以下错误。

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

这是我的代码。

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()

1 个答案:

答案 0 :(得分:1)

发件人确实是一个COM对象,而不是一个字符串。它具有NameAddress等属性。请注意,并非收件箱中的所有项目都是MailItem个对象 - 您还可以拥有MeetingItemReportItem个对象。如果您只想要MailItem个对象,请检查Class property = 43(OlObjectClass.olMail)