电子邮件身体有时是一个字符串,有时候是列表。为什么? [英] Email body is a string sometimes and a list sometimes. Why?

查看:188
本文介绍了电子邮件身体有时是一个字符串,有时候是列表。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序是用python编写的。我正在做的是我在postfix收到的每个电子邮件上运行一个脚本,并用电子邮件内容进行处理。 Procmail负责运行脚本,将电子邮件作为输入。当我将输入消息(可能是文本)转换为email_message对象(因为后者派上用场)时,问题开始了。我正在使用email.message_from_string(其中电子邮件是默认的电子邮件模块,附带python)。





import email
message = email.message_from_string(original_mail_content)
message_body = message.get_payload()



这个message_body是有时返回一个列表[email.message.Message实例,email.message.Message实例],有时返回一个字符串(传入电子邮件的实际内容)。为什么。甚至我再发现一次观察。当我浏览email.message.Message.get_payload()docstring时,我发现这个.. _

有效负载将是一个列表对象或一个字符串。如果您将
变为列表对象,您可以修改消息的有效载荷.....



那么如何使用通用方法来获取通过python的邮件体?请帮助我。

解决方案

嗯,答案是正确的,你应该阅读文档,但是一个通用的例子方式:

  def get_first_text_part(msg):
maintype = msg.get_content_maintype()
如果maintype = ='multipart':
作为msg.get_payload()中的一部分:
如果part.get_content_maintype()=='text':
return part.get_payload()
elif maintype =='text':
return msg.get_payload()

这很容易出现灾难,因为可以想象,部件本身可能有多部分,它只返回第一个文本部分,所以这可能是错误的,但你可以玩它。


My application is written in python. What I am doing is I am running a script on each email received by postfix and do something with the email content. Procmail is responsible for running the script taking the email as input. The problem started when I was converting the input message(may be text) to email_message object(because the latter comes in handy). I am using email.message_from_string (where email is the default email module, comes with python).

import email message = email.message_from_string(original_mail_content) message_body = message.get_payload()

This message_body is sometimes returning a list[email.message.Message instance,email.message.Message instance] and sometime returning a string(actual body content of the incoming email). Why is it. And even I found one more observation. When I was browsing through the email.message.Message.get_payload() docstring, I found this..
""" The payload will either be a list object or a string.If you mutate the list object, you modify the message's payload in place....."""

So how do I have generic method to get the body of email through python? Please help me out.

解决方案

Well, the answers are correct, you should read the docs, but for an example of a generic way:

def get_first_text_part(msg):
    maintype = msg.get_content_maintype()
    if maintype == 'multipart':
        for part in msg.get_payload():
            if part.get_content_maintype() == 'text':
                return part.get_payload()
    elif maintype == 'text':
        return msg.get_payload()

This is prone to some disaster, as it is conceivable the parts themselves might have multiparts, and it really only returns the first text part, so this might be wrong too, but you can play with it.

这篇关于电子邮件身体有时是一个字符串,有时候是列表。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆