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

时间:2011-03-10 12:27:54

标签: python utf-8 email

  

可能重复:
  string encode / decode

现在主题看起来像: =?UTF-8 2 B 4 0J / RgNC + 0LLQtdGA0LrQsA ==?=

2 个答案:

答案 0 :(得分:10)

答案 1 :(得分:9)

=?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: Проверка
相关问题