If we are sent this message and retrieve it via poplib, parsing its full text yields a
Message object just like the one we built to send. The message walk generator allows us
to step through each part, fetching their types and payloads:
>>> text # same as in prior interaction
'Content-Type: multipart/mixed; boundary="===============1574823535=="\nMIME-Ver...'
>>> from email.parser import Parser
>>> msg = Parser().parsestr(text)
>>> msg['from']
'Art <[email protected]>'
>>> for part in msg.walk():
... print(part.get_content_type())
... print(part.get_payload())
... print()
multipart/mixed
[<email.message.Message object at 0x015EC610>,
<email.message.Message object at0x015EC630>]
text/plain
nice red uniforms...
text/plain
line1
line2
line3
Multipart alternative messages (with text and HTML renditions of the same message)
can be composed and parsed in similar fashion. Because email clients are able to parse
and compose messages with a simple object-based API, they are freed to focus on user-
interface instead of text processing.
Unicode, Internationalization, and the Python 3.1 email Package
Now that I’ve shown you how “cool” the email package is, I unfortunately need to let
you know that it’s not completely operational in Python 3.1. The email package works
as shown for simple messages, but is severely impacted by Python 3.X’s Unicode/bytes
string dichotomy in a number of ways.
In short, the email package in Python 3.1 is still somewhat coded to operate in the realm
of 2.X str text strings. Because these have become Unicode in 3.X, and because some
tools that email uses are now oriented toward bytes strings, which do not mix freely
with str, a variety of conflicts crop up and cause issues for programs that depend upon
this module.
At this writing, a new version of email is being developed which will handle bytes and
Unicode encodings better, but the going consensus is that it won’t be folded back into
Python until release 3.3 or later, long after this book’s release. Although a few patches
926 | Chapter 13: Client-Side Scripting