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

(yzsuai) #1

bodyencoding = 'ascii'
try:
text.encode(bodyencoding) # try ascii first (or latin-1?)
except (UnicodeError, LookupError): # else use tuf8 as fallback (or config?)
bodyencoding = 'utf-8' # tbd: this is more limited than PyMailGUI


3.0: use utf8 for all attachments; we can't ask here


attachencodings = ['utf-8'] * len(attaches) # ignored for non-text parts


encode and send


sender = mailtools.SilentMailSender(smtpservername)
try:
sender.sendMessage(From, Tos, Subj, extraHdrs, text, attaches,
bodytextEncoding=bodyencoding,
attachesEncodings=attachencodings)
except:
commonhtml.errorpage('Send mail error')
else:
commonhtml.confirmationpage('Send mail')


This script gets mail header and text input information from the edit page’s form (or
from query parameters in an explicit URL) and sends the message off using Python’s
standard smtplib module, courtesy of the mailtools package. We studied mailtools in
Chapter 13, so I won’t say much more about it now. Note, though, that because we
are reusing its send call, sent mail is automatically saved in a sentmail.txt file on the
server; there are no tools for viewing this in PyMailCGI itself, but it serves as a log.


New in version 2.0, the saveAttachments function grabs any part files sent from the
browser and stores them in temporary local files on the server from which they will be
added to the mail when sent. We covered CGI upload in detail at the end of Chap-
ter 15 ; see that discussion for more on how the code here works (as well as its limitations
in Python 3.1 and this edition—we’re attaching simple text here to accommodate). The
business of attaching the files to the mail itself is automatic in mailtools.


A utility in commonhtml ultimately fetches the name of the SMTP server to receive the
message from either the mailconfig module or the script’s inputs (in a form field or
URL query parameter). If all goes well, we’re presented with a generated confirmation
page, as captured in Figure 16-4.


Open file sentmail.txt in PyMailCGI’s source directory if you want to see what the
resulting mail’s raw text looks like when sent (or fetch the message in an email client
with a raw text view, such as PyMailGUI). In this version, each attachment part is MIME
encoded per Base64 with UTF-8 Unicode encoding in the multipart message, but the
main text part is sent as simple ASCII if it works as such.


As we’ll see, this send mail script is also used to deliver reply and forward messages for
incoming POP mail. The user interface for those operations is slightly different for
composing new email from scratch, but as in PyMailGUI, the submission handler logic
has been factored into the same, shared code—replies and forwards are really just mail
send operations with quoted text and preset header fields.


Sending Mail by SMTP| 1245
Free download pdf