[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

To assist clients, Example 13-24 includes tools, which match message headers on de-
letions to ensure accuracy and perform general inbox synchronization tests on demand.
These tools are useful only to clients that retain the fetched email list as state informa-
tion. We’ll use these in the PyMailGUI client in Chapter 14. There, deletions use the
safe interface, and loads run the on-demand synchronization test; on detection of syn-
chronization errors, the inbox index is automatically reloaded. For now, see Exam-
ple 13-24 source code and comments for more details.


Note that the synchronization tests try a variety of matching techniques, but require
the complete headers text and, in the worst case, must parse headers and match many
header fields. In many cases, the single previously fetched message-id header field
would be sufficient for matching against messages in the server’s inbox. However, be-
cause this field is optional and can be forged to have any value, it might not always be
a reliable way to identify messages. In other words, a same-valued message-id may not
suffice to guarantee a match, although it can be used to identify a mismatch; in Exam-
ple 13-24, the message-id is used to rule out a match if either message has one, and they
differ in value. This test is performed before falling back on slower parsing and multiple
header matches.


Example 13-24. PP4E\Internet\Email\mailtools\mailFetcher.py


"""
###############################################################################
retrieve, delete, match mail from a POP server (see init for docs, test)
###############################################################################
"""


import poplib, mailconfig, sys # client's mailconfig on sys.path
print('user:', mailconfig.popusername) # script dir, pythonpath, changes


from .mailParser import MailParser # for headers matching (4E: .)
from .mailTool import MailTool, SilentMailTool # trace control supers (4E: .)


index/server msgnum out of synch tests


class DeleteSynchError(Exception): pass # msg out of synch in del
class TopNotSupported(Exception): pass # can't run synch test
class MessageSynchError(Exception): pass # index list out of sync


class MailFetcher(MailTool):
"""
fetch mail: connect, fetch headers+mails, delete mails
works on any machine with Python+Inet; subclass me to cache
implemented with the POP protocol; IMAP requires new class;
4E: handles decoding of full mail text on fetch for parser;
"""
def init(self, popserver=None, popuser=None, poppswd=None, hastop=True):
self.popServer = popserver or mailconfig.popservername
self.popUser = popuser or mailconfig.popusername
self.srvrHasTop = hastop
self.popPassword = poppswd # ask later if None


The mailtools Utility Package | 969
Free download pdf