Python解析原始电子邮件并获取正文内容

3

如何在没有HTML标记的情况下获取电子邮件正文。

我尝试使用以下代码解析邮件,但是我得到整个“------=_Part_2”部分作为正文。

我的代码

import email
message = email.message_from_string(text)
print_payload(message)

def print_payload(message):
    print('******')
    if message.is_multipart():
        for payload in message.get_payload():
            print_payload(payload)
    else:
        print message.get_payload()
        for part in message.walk():
            if part.get_content_type():
                body = str(part.get_payload())
                print(body)
    print('******')

实际邮件内容:

又一封测试邮件。
谢谢,
Munesh

原始邮件:

Return-Path: abc@mydomain.com Date: Mon, 18 Sep 2017 23:07:16 +0000 From: abc@mydomain.com To: xyz@mydomain.com Cc: abc@mydomain.com Message-ID: <1233.5.68566565@host.corp.mydomain.com> Subject: My email subject MIME-Version: 1.0 Content-Type: application/ms-tnef Content-Transfer-Encoding: binary X-MS-Exchange-Organization-SCL: -1 X-MS-Exchange-Organization-MessageDirectionality: Originating Thread-Topic: My email subject X-Forefront-Antispam-Report: SFV:SKI;SCL:-1; X-MS-PublicTrafficType: Email X-MS-Exchange-Organization-Antispam-Report: SFV:SKI;SCL:-1; Accept-Language: en-US Content-Language: en-US

------=_Part_2_123.456 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit

<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="Generator" content="Microsoft Word 14 (filtered medium)"><style><!-- /* Font Definitions */ @font-face
        {font-family:Calibri;
        panose-1:2 15 5 2 2 2 4 3 2 4;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal
        {margin:0in;
        margin-bottom:.0001pt;
        font-size:11.0pt;
        font-family:"Calibri","sans-serif";} a:link, span.MsoHyperlink
        {mso-style-priority:99;
        color:blue;
        text-decoration:underline;} a:visited, span.MsoHyperlinkFollowed
        {mso-style-priority:99;
        color:purple;
        text-decoration:underline;} span.EmailStyle17
        {mso-style-type:personal-compose;
        font-family:"Calibri","sans-serif";
        color:windowtext;} .MsoChpDefault
        {mso-style-type:export-only;
        font-family:"Calibri","sans-serif";} @page WordSection1
        {size:8.5in 11.0in;
        margin:1.0in 1.0in 1.0in 1.0in;} div.WordSection1
        {page:WordSection1;}
--></style><!--[if gte mso 9]><xml><o:shapedefaults v:ext="edit" spidmax="1026" /></xml><![endif]--><!--[if gte mso 9]><xml><o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1" /></o:shapelayout></xml><![endif]--></head><body lang="EN-US" link="blue" vlink="purple"><div class="WordSection1"><p class="MsoNormal">Another test mail.<o:p></o:p></p><p class="MsoNormal"><o:p>&nbsp;</o:p></p><p class="MsoNormal">Thanks,<o:p></o:p></p><p class="MsoNormal">Munesh<o:p></o:p></p><p class="MsoNormal"><o:p>&nbsp;</o:p></p></div></body></html>

------=_Part_2_123.456--

提前感谢您。

1个回答

4

使用BeautifulSoup库解析文本并不是太难。如果您没有这个库,请确保先pip install bs4安装它。之后,就不会太难了:

from bs4 import BeautifulSoup
def print_payload(message):
    print('******')
    if message.is_multipart():
        for payload in message.get_payload():
            print_payload(payload)
    else:
         print message.get_payload()
         for part in message.walk():
             if part.get_content_type():
                 body = str(part.get_payload())
                 soup = BeautifulSoup(body)
                 paragraphs = soup.find_all('p')
                 for paragraph in paragraphs:
                     print(paragraph.text)
    print('******')

BeautifulSoup的精华在于创建解析树,从中可以选择HTML元素。因此,如果您的电子邮件中有其他HTML元素,则可能还需要搜索它们以获取所有数据。但是对于这个简单的电子邮件,找到所有带有标签“p”的HTML元素就足够了。

谢谢你的解决方案。但是它只部分起作用。当我搜索标签“p”时,初始文本(如Part_2和Content-Type)也会被打印出来。你能指导我如何只获取邮件正文吗? - Munesh
嗯,我不确定为什么会发生这种情况。如果你跳过第一段会怎样呢?即:for paragraph in paragraphs[1:] - Bradley Robinson
段落[1:]可以工作。但这看起来更像是一个hack而不是一个适当的修复。无论如何感谢您。如果您找到更好的方法,请告诉我。 - Munesh
我承认,HTML是出了名难以解析的。你可能也可以使用正则表达式检查XML代码并排除任何看起来像XML的内容,但这样也看起来有点凌乱。 - Bradley Robinson
我正在使用text=True来过滤不需要的数据,使用以下代码:paragraphs_all = soup.find_all('p',text=False), paragraphs_extra = soup.find_all('p',text=True), paragraphs=set(paragraphs_all)-set(paragraphs_extra) - Munesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接