Skip to main content
 首页 » 编程设计

python之使用 IMAP 提取 header 错误 TypeError : initial_value must be str or None, not bytes

2024年08月26日32grandyang

这是我连接到 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 解析 header ?

请您参考如下方法:

替换

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

与

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

这应该可以让它在 Python 3.x.x 上运行

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

在 python 3 中,所有字符串都是 unicode,如果您接收到字节,则必须先将它们转换为 str 数据类型。 You can read more about that here