TypeError:初始值必须是str或none,而不是python 3中的字节?

TypeError:初始值必须是str或none,而不是python 3中的字节?,python,python-3.x,imaplib,Python,Python 3.x,Imaplib,这是我的密码: 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][

这是我的密码:

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

我用的是Python3,它显然是自动解码的。那么为什么我仍然收到这个错误消息呢

在这种情况下,您可能需要使用。

您可以尝试:

header_data = data[1][0][1].decode('utf-8')
我建议这样做,(Python 3)


您在哪一行收到该错误?msg=parser.parsestr(header\u data)这可以工作,谢谢。对于Python2,您不需要使用decode()命令
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"]