Using IMAP to extract headers error TypeError: initial_value must be str or None, not bytes

Using IMAP to extract headers error TypeError: initial_value must be str or None, not bytes

这是我连接到 gmail 并解析电子邮件的代码:

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. 如何将结果转换为字符串以便我可以使用 parser.parsestr 解析 headers?

替换

header_data = data[1][0][1]

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

这应该可以在 Python 3.x.x

上运行

这是迁移代码使其成为Python3的痛点之一,但是一旦理解了它,就非常容易修复。此外,如果您进行更改,它将破坏与 python 2.x.x

的兼容性

在python3中所有的字符串都是unicode,如果你接收字节,你必须先将它们转换成str数据类型。 You can read more about that here