Python 3中出现TypeError: initial_value must be str or none, not bytes错误?

7

以下是我的代码:

import imaplib
from email.parser import HeaderParser
conn = imaplib.IMAP4_SSL('imap.gmail.com')
conn.login('example@gmail.com', 'password')
conn.select()
conn.search(None, 'ALL')
data = conn.fetch('1', '(BODY[HEADER])')
header_data = data[1][0][1]
parser = HeaderParser()
msg = parser.parsestr(header_data)

我得到了以下错误信息:

TypeError: initial_value must be str or none, not bytes

我正在使用Python 3,它据说可以自动解码。那么为什么我还是收到了这个错误信息?


你在哪一行收到了那个错误? - Anthony Forloney
msg = parser.parsestr(header_data)msg = parser.parsestr(header_data) - user4530588
3个回答

16

你可以尝试:

header_data = data[1][0][1].decode('utf-8')

2
可以了,谢谢。在Python 2中,你不需要使用decode()方法。 - Desmond

14
我建议这样做(Python 3)。
typ, data = conn.fetch('1', '(RFC822)') # will read the first email
email_content = data[0][1] 
msg = email.message_from_bytes(email_content) # this needs to be corrected in your case 
emailDate =  msg["Date"]
emaiSubject = msg["Subject"]

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接