Skip to main content
 首页 » 编程设计

python之如何在 Python 中解码二进制编码的邮件消息

2025年05月04日28yxwkf

我正在编写一个处理传入邮件的 Google App 引擎应用程序,这是我目前用来处理邮件消息的代码:

for content_type, body in email_bodies: 
#8bit bug in mail messages - see bug report here 
#http://code.google.com/p/googleappengine/issues/detail?id=2383 
if body.encoding == '8bit': 
    body.encoding = '7bit' 
 
#test for html content 
if content_type == "text/html": 
    #parse html result 
 
if content_type == "text/plain": 
    decoded_msg_body = body.decode() 

然而,我刚刚收到一条使用二进制编码方案的消息,当我的程序尝试使用 body.decode() 处理该消息时,我收到了一个 UnknownEncodingError。这个程序应该如何解析二进制内容类型?另外,如何在我的本地版本的 GAE 上模仿这种消息类型,以便调试和测试它?

感谢您的帮助, 凯文

请您参考如下方法:

与其重新发明轮子,不如尝试使用 Python 内置的电子邮件解析器。

http://docs.python.org/library/email.parser.html

它旨在处理将各种不同的电子邮件格式转换为良好的 Python 对象所涉及的提升。使用它进行解析,您将获得可预测的对象。

email 模块不做消息的发送和接收,它只是帮助把它们放在一起并解析出来。