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

(yzsuai) #1

Example 13-22. PP4E\Internet\Email\mailtools\mailTool.py


"""
###############################################################################
common superclasses: used to turn trace massages on/off
###############################################################################
"""


class MailTool: # superclass for all mail tools
def trace(self, message): # redef me to disable or log to file
print(message)


class SilentMailTool: # to mixin instead of subclassing
def trace(self, message):
pass


MailSender Class


The class used to compose and send messages is coded in Example 13-23. This module
provides a convenient interface that combines standard library tools we’ve already met
in this chapter—the email package to compose messages with attachments and en-
codings, and the smtplib module to send the resulting email text. Attachments are
passed in as a list of filenames—MIME types and any required encodings are deter-
mined automatically with the module mimetypes. Moreover, date and time strings are
automated with an email.utils call, and non-ASCII headers are encoded per email,
MIME, and Unicode standards. Study this file’s code and comments for more on its
operation.


Unicode issues for attachments, save files, and headers


This is also where we open and add attachment files, generate message text, and save
sent messages to a local file. Most attachment files are opened in binary mode, but as
we’ve seen, some text attachments must be opened in text mode because the current
email package requires them to be str strings when message objects are created. As we
also saw earlier, the email package requires attachments to be str text when mail text
is later generated, possibly as the result of MIME encoding.


To satisfy these constraints with the Python 3.1 email package, we must apply the two
fixes described earlier— part file open calls select between text or binary mode (and
thus read str or bytes) based upon the way email will process the data, and MIME
encoding calls for binary data are augmented to decode the result to ASCII text. The
latter of these also splits the Base64 text into lines here for binary parts (unlike email),
because it is otherwise sent as one long line, which may work in some contexts, but
causes problems in some text editors if the raw text is viewed.


Beyond these fixes, clients may optionally provide the names of the Unicode encoding
scheme associated with the main text part and each text attachment part. In Chap-
ter 14’s PyMailGUI, this is controlled in the mailconfig user settings module, with
UTF-8 used as a fallback default whenever user settings fail to encode a text part. We


The mailtools Utility Package | 959
Free download pdf