- poplib and imaplib for fetching email
- smtplib for sending email
- The email module package for parsing email and constructing email
These modules are related: for nontrivial messages, we typically use email to parse mail
text which has been fetched with poplib and use email to compose mail text to be sent
with smtplib. The email package also handles tasks such as address parsing, date and
time formatting, attachment formatting and extraction, and encoding and decoding of
email content (e,g, uuencode, Base64). Additional modules handle more specific tasks
(e.g., mimetypes to map filenames to and from content types).
In the next few sections, we explore the POP and SMTP interfaces for fetching and
sending email from and to servers, and the email package interfaces for parsing and
composing email message text. Other email interfaces in Python are analogous and are
documented in the Python library reference manual.§
Unicode in Python 3.X and Email Tools
In the prior sections of this chapter, we studied how Unicode encodings can impact
scripts using Python’s ftplib FTP tools in some depth, because it illustrates the impli-
cations of Python 3.X’s Unicode string model for real-world programming. In short:
- All binary mode transfers should open local output and input files in binary mode
(modes wb and rb). - Text-mode downloads should open local output files in text mode with explicit
encoding names (mode w, with an encoding argument that defaults to latin1 within
ftplib itself). - Text-mode uploads should open local input files in binary mode (mode rb).
The prior sections describe why these rules are in force. The last two points here differ
for scripts written originally for Python 2.X. As you might expect, given that the un-
derlying sockets transfer byte strings today, the email story is somewhat convoluted for
Unicode in Python 3.X as well. As a brief preview:
Fetching
The poplib module returns fetched email text in bytes string form. Command text
sent to the server is encoded per UTF8 internally, but replies are returned as raw
binary bytes and not decoded into str text.
§IMAP, or Internet Message Access Protocol, was designed as an alternative to POP, but it is still not as widely
available today, and so it is not presented in this text. For instance, major commercial providers used for this
book’s examples provide only POP (or web-based) access to email. See the Python library manual for IMAP
server interface details. Python used to have a RFC822 module as well, but it’s been subsumed by the
email package in 3.X.
900 | Chapter 13: Client-Side Scripting