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

(yzsuai) #1

"""


import cgi
import loadmail, commonhtml
from externs import mailtools
from secret import encode # user-defined encoder module
MaxHdr = 35 # max length of email hdrs in list


only pswd comes from page here, rest usually in module


formdata = cgi.FieldStorage()
mailuser, mailpswd, mailsite = commonhtml.getstandardpopfields(formdata)
parser = mailtools.MailParser()


try:
newmails = loadmail.loadmailhdrs(mailsite, mailuser, mailpswd)
mailnum = 1
maillist = [] # or use enumerate()
for mail in newmails: # list of hdr text
msginfo = []
hdrs = parser.parseHeaders(mail) # email.message.Message
addrhdrs = ('From', 'To', 'Cc', 'Bcc') # decode names only
for key in ('Subject', 'From', 'Date'):
rawhdr = hdrs.get(key, '?')
if key not in addrhdrs:
dechdr = parser.decodeHeader(rawhdr) # 3.0: decode for display
else: # encoded on sends
dechdr = parser.decodeAddrHeader(rawhdr) # email names only
msginfo.append(dechdr[:MaxHdr])
msginfo = ' | '.join(msginfo)
maillist.append((msginfo, commonhtml.urlroot + 'onViewListLink.py',
{'mnum': mailnum,
'user': mailuser, # data params
'pswd': encode(mailpswd), # pass in URL
'site': mailsite})) # not inputs
mailnum += 1
commonhtml.listpage(maillist, 'mail selection list')
except:
commonhtml.errorpage('Error loading mail index')


This script’s main purpose is to generate a selection list page for the user’s email ac-
count, using the password typed into the prior page (or passed in a URL). As usual with
encapsulation, most of the details are hidden in other files:


loadmail.loadmailhdrs
Reuses the mailtools module package from Chapter 13 to fetch email with the POP
protocol; we need a message count and mail headers here to display an index list.
In this version, the software fetches only mail header text to save time, not full mail
messages (provided your server supports the TOP command of the POP interface,
and most do—if not, see mailconfig to disable this).


1252 | Chapter 16: The PyMailCGI Server

Free download pdf