Updating the pymail Console Client
As a final email example in this chapter, and to give a better use case for the mail
tools module package of the preceding sections, Example 13-27 provides an updated
version of the pymail program we met earlier (Example 13-20). It uses our mailtools
package to access email, instead of interfacing with Python’s email package directly.
Compare its code to the original pymail in this chapter to see how mailtools is employed
here. You’ll find that its mail download and send logic is substantially simpler.
Example 13-27. PP4E\Internet\Email\pymail2.py
#!/usr/local/bin/python
"""
################################################################################
pymail2 - simple console email interface client in Python; this version uses
the mailtools package, which in turn uses poplib, smtplib, and the email package
for parsing and composing emails; displays first text part of mails, not the
entire full text; fetches just mail headers initially, using the TOP command;
fetches full text of just email selected to be displayed; caches already
fetched mails; caveat: no way to refresh index; uses standalone mailtools
objects - they can also be used as superclasses;
################################################################################
"""
import mailconfig, mailtools
from pymail import inputmessage
mailcache = {}
def fetchmessage(i):
try:
fulltext = mailcache[i]
except KeyError:
fulltext = fetcher.downloadMessage(i)
mailcache[i] = fulltext
return fulltext
def sendmessage():
From, To, Subj, text = inputmessage()
sender.sendMessage(From, To, Subj, [], text, attaches=None)
def deletemessages(toDelete, verify=True):
print('To be deleted:', toDelete)
if verify and input('Delete?')[:1] not in ['y', 'Y']:
print('Delete cancelled.')
else:
print('Deleting messages from server...')
fetcher.deleteMessages(toDelete)
def showindex(msgList, msgSizes, chunk=5):
count = 0
for (msg, size) in zip(msgList, msgSizes): # email.message.Message, int
count += 1 # 3.x iter ok here
print('%d:\t%d bytes' % (count, size))
for hdr in ('From', 'To', 'Date', 'Subject'):
986 | Chapter 13: Client-Side Scripting