There isn’t much new here—just a combination of user-interface logic and tools we’ve
already met, plus a handful of new techniques:
Loads
This client loads all email from the server into an in-memory Python list only once,
on startup; you must exit and restart to reload newly arrived email.
Saves
On demand, pymail saves the raw text of a selected message into a local file, whose
name you place in the mailconfig module of Example 13-17.
Deletions
We finally support on-request deletion of mail from the server here: in pymail, mails
are selected for deletion by number, but are still only physically removed from your
server on exit, and then only if you verify the operation. By deleting only on exit,
we avoid changing mail message numbers during a session—under POP, deleting
a mail not at the end of the list decrements the number assigned to all mails fol-
lowing the one deleted. Since mail is cached in memory by pymail, future operations
on the numbered messages in memory can be applied to the wrong mail if deletions
were done immediately.#
Parsing and composing messages
pymail now displays just the payload of a message on listing commands, not the
entire raw text, and the mail index listing only displays selected headers parsed out
of each message. Python’s email package is used to extract headers and content
from a message, as shown in the prior section. Similarly, we use email to compose
a message and ask for its string to ship as a mail.
By now, I expect that you know enough to read this script for a deeper look, so instead
of saying more about its design here, let’s jump into an interactive pymail session to see
how it works.
Running the pymail Console Client
Let’s start up pymail to read and delete email at our mail server and send new messages.
pymail runs on any machine with Python and sockets, fetches mail from any email server
with a POP interface on which you have an account, and sends mail via the SMTP server
you’ve named in the mailconfig module we wrote earlier (Example 13-17).
Here it is in action running on my Windows laptop machine; its operation is identical
on other machines thanks to the portability of both Python and its standard library.
#There will be more on POP message numbers when we study mailtools later in this chapter. Interestingly,
the list of message numbers to be deleted need not be sorted; they remain valid for the duration of the delete
connection, so deletions earlier in the list don’t change numbers of messages later in the list while you are
still connected to the POP server. We’ll also see that some subtle issues may arise if mails in the server inbox
are deleted without pymail’s knowledge (e.g., by your ISP or another email client); although very rare, suffice
it to say for now that deletions in this script are not guaranteed to be accurate.
952 | Chapter 13: Client-Side Scripting