Though primitive, this script illustrates the basics of reading email in Python. To es-
tablish a connection to an email server, we start by making an instance of the pop
lib.POP3 object, passing in the email server machine’s name as a string:
server = poplib.POP3(mailserver)
If this call doesn’t raise an exception, we’re connected (by socket) to the POP server
listening on POP port number 110 at the machine where our email account lives.
The next thing we need to do before fetching messages is tell the server our username
and password; notice that the password method is called pass_. Without the trailing
underscore, pass would name a reserved word and trigger a syntax error:
server.user(mailuser) # connect, log in to mail server
server.pass_(mailpasswd) # pass is a reserved word
To keep things simple and relatively secure, this script always asks for the account
password interactively; the getpass module we met in the FTP section of this chapter
is used to input but not display a password string typed by the user.
Once we’ve told the server our username and password, we’re free to fetch mailbox
information with the stat method (number messages, total bytes among all messages)
and fetch the full text of a particular message with the retr method (pass the message
number—they start at 1). The full text includes all headers, followed by a blank line,
followed by the mail’s text and any attached parts. The retr call sends back a tuple that
includes a list of line strings representing the content of the mail:
msgCount, msgBytes = server.stat()
hdr, message, octets = server.retr(i+1) # octets is byte count
We close the email server connection by calling the POP object’s quit method:
server.quit() # else locked till timeout
Notice that this call appears inside the finally clause of a try statement that wraps the
bulk of the script. To minimize complications associated with changes, POP servers
lock your email inbox between the time you first connect and the time you close your
connection (or until an arbitrary, system-defined timeout expires). Because the POP
quit method also unlocks the mailbox, it’s crucial that we do this before exiting,
whether an exception is raised during email processing or not. By wrapping the action
in a try/finally statement, we guarantee that the script calls quit on exit to unlock the
mailbox to make it accessible to other processes (e.g., delivery of incoming email).
Fetching Messages
Here is the popmail script of Example 13-18 in action, displaying two messages in my
account’s mailbox on machine pop.secureserver.net—the domain name of the mail
server machine used by the ISP hosting my learning-python.com domain name, as
configured in the module mailconfig. To keep this output reasonably sized, I’ve omitted
or truncated a few irrelevant message header lines here, including most of the
906 | Chapter 13: Client-Side Scripting