我正在使用
我的代码是基于以下帖子编写的:Clearly documented reading of emails functionality with python win32com outlook 然而,我只能获取
win32com.client
与Outlook进行交互。我已经成功地检索到了邮件的正文和主题。我的代码是基于以下帖子编写的:Clearly documented reading of emails functionality with python win32com outlook 然而,我只能获取
body
和subject
,其他任何东西都会返回<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()
message.Sender
无法获取发件人信息。相反,我使用message.SenderName
获取他们的姓名和message.SenderEmailAddress
获取其电子邮件地址。我还建议对发件人名称使用unidecode
包,因为有些人的名称中可能带有特殊字符:unidecode(message.SenderName)
。此外,附上一个文档关于MailItem属性。 - Scratch'N'Purr