Printing the full text of a message at the interactive prompt is easy once it’s fetched:
simply decode each line to a normal string as it is printed, like our pop mail script did,
or concatenate the line strings returned by retr or top adding a newline between; any
of the following will suffice for an open POP server object:
>>> info, msg, oct = connection.retr(1) # fetch first email in mailbox
>>> for x in msg: print(x.decode()) # four ways to display message lines
>>> print(b'\n'.join(msg).decode())
>>> x = [print(x.decode()) for x in msg]
>>> x = list(map(print, map(bytes.decode, msg)))
Parsing email text to extract headers and components is more complex, especially for
mails with attached and possibly encoded parts, such as images. As we’ll see later in
this chapter, the standard library’s email package can parse the mail’s full or headers
text after it has been fetched with poplib (or imaplib).
See the Python library manual for details on other POP module tools. As of Python 2.4,
there is also a POP3_SSL class in the poplib module that connects to the server over an
SSL-encrypted socket on port 995 by default (the standard port for POP over SSL). It
provides an identical interface, but it uses secure sockets for the conversation where
supported by servers.
SMTP: Sending Email
There is a proverb in hackerdom that states that every useful computer program even-
tually grows complex enough to send email. Whether such wisdom rings true or not
in practice, the ability to automatically initiate email from within a program is a pow-
erful tool.
For instance, test systems can automatically email failure reports, user interface pro-
grams can ship purchase orders to suppliers by email, and so on. Moreover, a portable
Python mail script could be used to send messages from any computer in the world
with Python and an Internet connection that supports standard email protocols. Free-
dom from dependence on mail programs like Outlook is an attractive feature if you
happen to make your living traveling around teaching Python on all sorts of computers.
Luckily, sending email from within a Python script is just as easy as reading it. In fact,
there are at least four ways to do so:
Calling os.popen to launch a command-line mail program
On some systems, you can send email from a script with a call of the form:
os.popen('mail -s "xxx" [email protected]', 'w').write(text)
As we saw earlier in the book, the popen tool runs the command-line string passed
to its first argument, and returns a file-like object connected to it. If we use an open
mode of w, we are connected to the command’s standard input stream—here, we
write the text of the new mail message to the standard Unix mail command-line
910 | Chapter 13: Client-Side Scripting