由于我having problems具有标准GAE的电子邮件功能,当电子邮件主题为UTF-8编码时,我正在尝试手动处理它:
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))
我能正确地做到吗?我应该解码主题吗?或者是由电子邮件解析器自动完成的?
答案 0 :(得分: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')