我正在尝试制作一个简单的程序来检查和显示未读邮件,但是在尝试获取主题和发件人地址时遇到问题。对于发件人,我尝试过这种方法:
import email
m = server.fetch([a], ['RFC822'])
#a is variable with email id
msg = email.message_from_string(m[a], ['RFC822'])
print msg['from']
from email.utils import parseaddr
print parseaddr(msg['from'])
但它没有用。我收到了这个错误:
Traceback (most recent call last):
File "C:/Users/ExampleUser/AppData/Local/Programs/Python/Python35-32/myprogram.py", line 20, in <module>
msg = email.message_from_string(m[a], ['RFC822'])
File "C:\Users\ExampleUser\AppData\Local\Programs\Python\Python35-32\lib\email\__init__.py", line 38, in message_from_string
return Parser(*args, **kws).parsestr(s)
File "C:\Users\ExampleUser\AppData\Local\Programs\Python\Python35-32\lib\email\parser.py", line 68, in parsestr
return self.parse(StringIO(text), headersonly=headersonly)
TypeError: initial_value must be str or None, not dict
我也用过这个:
print(server.fetch([a], ['BODY[HEADER.FIELDS (FROM)]']))
但结果是这样的:
defaultdict(<class 'dict'>, {410: {b'BODY[HEADER.FIELDS ("FROM")]': b'From: "=?utf-8?q?senderexample?=" <sender@example.com>\r\n\r\n', b'SEQ': 357}, 357: {b'SEQ': 357, b'FLAGS': (b'\\Seen',)}})
有没有办法修复第一种方法,或者使第二种方法的结果看起来像:
Sender Example <sender@example.com>
? 而且我也不知道如何获取电子邮件主题。但我想它与发件人相同,但有其他论点。所以我唯一需要的就是这些论点。