1
我試圖做一個簡單的程序來檢查並顯示未讀消息,但我在嘗試獲取主題和發件人地址時遇到問題。 對於寄件人我試過這個方法:IMAPClient - 如何獲取主題和發件人?
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?=" <[email protected]>\r\n\r\n', b'SEQ': 357}, 357: {b'SEQ': 357, b'FLAGS': (b'\\Seen',)}})
有沒有辦法來修復第一種方法,或使第二個看起來像這樣的結果:
Sender Example <[email protected]>
? 而且我也不知道如何獲得電子郵件主題。但我想它和發件人一樣,但是有其他論點。所以我唯一需要的就是這些論點。