0

我从我的谷歌帐户向我的 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')

然后消息正文正确显示。但是我应该如何提取编码?

4

1 回答 1

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)
于 2013-04-21T07:54:02.603 回答