The email Package

(New in 2.2) Tools for manipulation of all sorts of email messages.

The email package replaces simpler modules, such as rfc822 and mimetools, with a much more flexible message object, and associated parsers.

Parsing Messages 

The easiest way to parse messages is to use the message_from_file or message_from_string helpers in the email toplevel module. The former takes a file handle, the latter a string object:

Parsing a plain message

import email

simple_message = """\
From: fredrik
Content-Type: text/plain

Hello!
"""

msg = email.message_from_string(simple_message)
# msg = email.message_from_file(open(filename))

print "head", msg.items()
print "type", repr(msg.get_content_type())
print "body", repr(msg.get_payload())

## head [('From', 'fredrik'), ('Content-Type', 'text/plain')]
## type 'text/plain'
## body 'Hello!\n'

The message object (an instance of the email.Message class) uses a dictionary-style interface to access header fields. There are also additional get methods for specific header fields, such as content-type.

In addition to the header fields, the message object also contains either a single payload, or for “multipart” messages, a sequence of sub-messages. The is_multipart() method can be used to check if an instance contains a single message or a sequence; the get_payload() method fetches the actual payload.

To traverse all submessages in a multipart message, you can use the walk() method:

Parsing a multipart message

import email

multipart_message = """\
From: fredrik
Content-Type: multipart/alternative; boundary="BOUNDARY"

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

Hello!

--BOUNDARY
Content-Type: text/html
Content-Transfer-Encoding: quoted-printable

<p>Hello!</p>
--BOUNDARY--
"""

msg = email.message_from_string(multipart_message)

for part in msg.walk():
    print "type", repr(part.get_content_type())
    print "body", repr(part.get_payload())

type 'multipart/alternative'
body [<email.Message.Message instance at 0x00C09D78>,
      <email.Message.Message instance at 0x00C09E68>]
type 'text/plain'
body 'Hello!\n'
type 'text/html'
body '<p>Hello!</p>'

Package Contents 

email.base64MIME

email.Charset

email.Encoders

email.Errors

email.Generator

email.Header

email.Iterators

email.Message

email.MIMEAudio

email.MIMEBase

email.MIMEImage

email.MIMEMessage

email.MIMEMultipart

email.MIMENonMultipart

email.MIMETextemail.Parser

email.quopriMIME

email.Utils