Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

It seems easy to get the

    From
    To
    Subject

etc via

    import email
    b = email.message_from_string(a)
    bbb = b['from']
    ccc = b['to']

assuming that "a" is the raw-email string which looks something like this.

    a = """From [email protected] Thu Jul 25 19:28:59 2013
    Received: from a1.local.tld (localhost [127.0.0.1])
        by a1.local.tld (8.14.4/8.14.4) with ESMTP id r6Q2SxeQ003866
        for <[email protected]>; Thu, 25 Jul 2013 19:28:59 -0700
    Received: (from [email protected])
        by a1.local.tld (8.14.4/8.14.4/Submit) id r6Q2Sxbh003865;
        Thu, 25 Jul 2013 19:28:59 -0700
    From: [email protected]
    Subject: oooooooooooooooo
    To: [email protected]
    Cc: 
    X-Originating-IP: 192.168.15.127
    X-Mailer: Webmin 1.420
    Message-Id: <[email protected]>
    Date: Thu, 25 Jul 2013 19:28:59 -0700 (PDT)
    MIME-Version: 1.0
    Content-Type: multipart/mixed; boundary="bound1374805739"

    This is a multi-part message in MIME format.

    --bound1374805739
    Content-Type: text/plain
    Content-Transfer-Encoding: 7bit

    ooooooooooooooooooooooooooooooooooooooooooooooo
    ooooooooooooooooooooooooooooooooooooooooooooooo
    ooooooooooooooooooooooooooooooooooooooooooooooo

    --bound1374805739--"""

THE QUESTION

how do you get the Body of this email via python ?

So far this is the only code i am aware of but i have yet to test it.

    if email.is_multipart():
        for part in email.get_payload():
            print part.get_payload()
    else:
        print email.get_payload()

is this the correct way ?

or maybe there is something simpler such as...

    import email
    b = email.message_from_string(a)
    bbb = b['body']

?

Use Message.get_payload

    b = email.message_from_string(a)
    if b.is_multipart():
        for payload in b.get_payload():
            # if payload.is_multipart(): ...
            print payload.get_payload()
    else:
        print b.get_payload()

From: stackoverflow.com/q/17874360

Back to homepage or read more recommendations: