unicode 内置函数在 Python 3 中不存在 - 这就是为什么您会收到异常 NameError: name 'unicode' is not defined。在 Python 3 中,unicode 的等价物是 str。
与unicode 一样,str 接受一个编码参数,并将尝试使用提供的编码解码一个字节串。如果您将str 实例传递给str 进行解码,您将得到TypeError: decoding str is not supported。
email.header.decode_header 的输出可能同时包含 str 和 bytes 实例,因此您的理解需要能够同时处理这两个实例:
print('%-8s: %s' % ('subject'.upper(), ''.join(t[0] if isinstance(t[0], str) else str(t[0], t[1] or default_charset) for t in dh)))
(在 Python 3 中,最好将 default_charset 设置为 'utf-8')。
最后,如果您控制消息对象的创建方式,则可以通过在创建消息时指定策略对象来自动解码标头(Python 3.5+)。
>>> from email.policy import default
>>> with open('message.eml', 'rb') as f:
... msg = email.message_from_bytes(f.read(), policy=default)
>>>
>>> for x in msg.raw_items():print(x)
...
('Subject', 'Ayons asperges pour le =?utf-8?q?d=C3=A9jeuner?=')
('From', '=?utf-8?q?Pep=C3=A9?= Le Pew <pepe@example.com>')
('To', 'Penelope Pussycat <penelope@example.com>,\n Fabrette Pussycat <fabrette@example.com>')
('Content-Type', 'text/plain; charset="utf-8"')
('Content-Transfer-Encoding', 'quoted-printable')
('MIME-Version', '1.0')
>>> msg['from']
'Pepé Le Pew <pepe@example.com>'
>>> msg['subject']
'Ayons asperges pour le déjeuner'
(消息数据取自电子邮件examples)。