我将来自我的Google帐户的邮件发送到我的GAE电子邮件:
Content-Type: text/plain; charset=KOI8-R
Content-Transfer-Encoding: base64
然后使用以下代码:
logging.debug('Received personal inbound mail from: %s, to: %s, subject: %s' % (mail_message.sender, mail_message.to, mail_message.subject))
body = ''
for b in mail_message.bodies('text/plain'):
body_type, pl = b # content encoding, plain text
if pl.encoding:
body = pl.payload.decode(pl.encoding)
else:
body = pl.payload
if body:
logging.debug('Inbound personal mail body: %s' % (body))
结果我在控制台中看到以下内容:
Received personal inbound mail from: Test <test@example.com>, to: test@myappid.appspotmail.com, subject: Readable russian text
Inbound personal mail body: ������, ��� �������� ���������
即。主体是可读的,但身体不是。
当我查看收到的内容时,我会看到以下内容:
text/plain, From nobody Mon Apr 15 17:15:34 2013
content-transfer-encoding: base64
MIME-Version: 1.0
Content-Type: text/plain; charset="koi8-r"
8NLJ18XULCDc1M8g1MXT1M/Xz8Ug08/Pwt3
如果我这样做:
body = pl.payload.decode(pl.encoding).decode('koi8-r')
然后正确显示邮件正文。但是我应该如何提取编码?
答案 0 :(得分:0)
结果,我使用了以下解决方案:
if msg.is_multipart():
for part in msg.walk():
if part.get_content_type() and part.get_content_type()=='text/plain': # ignore text/html
charset = part.get_content_charset()
body = part.get_payload(decode=True).decode(charset)
else:
body = msg.get_payload(decode=True)
body = body.decode('utf-8')
并且为了在开发人员的管理控制台(在Windows 7下)正确显示俄语文本:
def logging_debug(what):
''' Function to support cp866 encoding in developers admin console
'''
if os.environ.get('SERVER_SOFTWARE','').startswith('Devel'):
logging.debug(what.encode('cp866'))
else:
logging.debug(what)