0

由于当电子邮件主题为 UTF-8 编码时,标准 GAE 的电子邮件功能出现问题,因此我尝试手动处理它

msg_encoding = self.request.headers['Content-Type'].split('charset=')[1] # message/rfc822; charset=UTF-8
msg = email.message_from_string(self.request.body)
if msg:
    logging.debug(msg.get_content_charset()) # None
    logging.debug(msg['to'])
    logging.debug(msg['from'])
    logging.debug(msg['Subject'].decode(msg_encoding))

我做对了吗?我应该解码主题吗?还是由电子邮件解析器自动完成?

4

1 回答 1

2

以下简化代码(仅限文本/纯文本,无附件)对我很有效:

class InboundMailHandler(InboundMailHandler):
    def post(self):
        msg = email.message_from_string(self.request.body)
        if msg:
            charset = 'utf-8'
            from_realname, from_emailaddr = email.utils.parseaddr(msg['from'])
            to_realname, to_emailaddr = email.utils.parseaddr(msg['to'])
            # parse e-mail body, look for text/plain part only
            body = ''
            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(part.get_content_charset())
            else:
                body = msg.get_payload(decode=True)
                body = body.decode('utf-8')
            subject, encoding = email.header.decode_header(msg['subject'])[0]
            if encoding != None:
                subject = subject.decode(encoding)
            else:
                subject = subject.decode('utf-8')
于 2013-04-21T07:47:19.763 回答