Pergunta

I send message from my google account to my GAE e-mail:

Content-Type: text/plain; charset=KOI8-R
Content-Transfer-Encoding: base64

Then use the following code:

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))

In result I see the following in the console:

Received personal inbound mail from: Test <test@example.com>, to: test@myappid.appspotmail.com, subject: Readable russian text
Inbound personal mail body: ������, ��� �������� ���������

I.e. subject is readable, but body is not.

When I check what I receive, I see the following:

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

If I do:

body = pl.payload.decode(pl.encoding).decode('koi8-r')

then message body is displayed correctly. But how should I extract the encoding?

Foi útil?

Solução

In result, I've used the following solution:

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')

and in order to display Russian text correctly in developer's admin console (under 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)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top