[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

In this edition, we will support Unicode encodings of text parts and headers in messages
composed, and respect the Unicode encodings in text parts and mail headers of mes-
sages fetched. To make this work with the partially crippled email package in
Python 3.1, though, we’ll apply the following Unicode policies in various email clients
in this book:



  • Use user preferences and defaults for the preparse decoding of full mail text fetched
    and encoding of text payloads sent.

  • Use header information, if available, to decode the bytes payloads returned by
    get_payload when text parts must be treated as str text, but use binary mode files
    to finesse the issue in other contexts.

  • Use formats prescribed by email standard to decode and encode message headers
    such as From and Subject if they are not simple text.

  • Apply the fix described to work around the message text generation issue for binary
    parts.

  • Special-case construction of text message objects according to Unicode types and
    email behavior.


These are not necessarily complete solutions. For example, some of this edition’s email
clients allow for Unicode encodings for both text attachments and mail headers, but
they do nothing about encoding the full text of messages sent beyond the policies in-
herited from smtplib and implement policies that might be inconvenient in some use
cases. But as we’ll see, despite their limitations, our email clients will still be able to
handle complex email tasks and a very large set of emails.


Again, since this story is in flux in Python today, watch this book’s website for updates
that may improve or be required of code that uses email in the future. A future email
may handle Unicode encodings more accurately. Like Python 3.X, though, backward
compatibility may be sacrificed in the process and require updates to this book’s code.
For more on this issue, see the Web as well as up-to-date Python release notes.


Although this quick tour captures the basic flavor of the interface, we need to step up
to larger examples to see more of the email package’s power. The next section takes us
on the first of those steps.


A Console-Based Email Client


Let’s put together what we’ve learned about fetching, sending, parsing, and composing
email in a simple but functional command-line console email tool. The script in Ex-
ample 13-20 implements an interactive email session—users may type commands to
read, send, and delete email messages. It uses poplib and smtplib to fetch and send,
and uses the email package directly to parse and compose.


A Console-Based Email Client | 947
Free download pdf