如何将邮件主题从“?UTF-8?...?=”转换为可读字符串?

5 投票
2 回答
16751 浏览
提问于 2025-04-16 13:26

可能是重复的问题:
字符串编码/解码

现在这个内容看起来像这样:
=?UTF-8?B?0J/RgNC+0LLQtdGA0LrQsA==?=

2 个回答

11

也许你可以使用 decode_header 这个函数:http://docs.python.org/library/email.header.html#email.header.decode_header

11

=?UTF-8?B??= 之间的部分是一个经过 base64 编码的字符串。你需要把这一部分提取出来,然后进行解码。

import base64

#My buggy SSH account needs this to write unicode output, you hopefully won't
import sys
import codecs
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)


encoded = '=?UTF-8?B?0J/RgNC+0LLQtdGA0LrQsA==?='
prefix = '=?UTF-8?B?'
suffix = '?='

#extract the data part of the string
middle = encoded[len(prefix):len(encoded)-len(suffix)]
print "Middle: %s" % middle

#decode the bytes
decoded = base64.b64decode(middle)
#decode the utf-8
decoded = unicode(decoded, 'utf8')

print "Decoded: %s" % decoded

输出结果:

Middle: 0J/RgNC+0LLQtdGA0LrQsA==
Decoded: Проверка

撰写回答