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

(yzsuai) #1
Does Anybody Really Know What Time It Is?
In the prior version of the smtpmail script of Example 13-19, a simple date format was
used for the Date email header that didn’t quite follow the SMTP date formatting
standard:
>>> import time
>>> time.asctime()
'Wed May 05 17:52:05 2010'
Most servers don’t care and will let any sort of date text appear in date header lines, or
even add one if needed. Clients are often similarly forgiving, but not always; one of my
ISP webmail programs shows dates correctly anyhow, but another leaves such ill-
formed dates blank in mail displays. If you want to be more in line with the standard,
you could format the date header with code like this (the result can be parsed with
standard tools such as the time.strptime call):
import time
gmt = time.gmtime(time.time())
fmt = '%a, %d %b %Y %H:%M:%S GMT'
str = time.strftime(fmt, gmt)
hdr = 'Date: ' + str
print(hdr)
The hdr variable’s value looks like this when this code is run:
Date: Wed, 05 May 2010 21:49:32 GMT
The time.strftime call allows arbitrary date and time formatting; time.asctime is just
one standard format. Better yet, do what smtpmail does now—in the newer email pack-
age (described in this chapter), an email.utils call can be used to properly format date
and time automatically. The smtpmail script uses the first of the following format
alternatives:
>>> import email.utils
>>> email.utils.formatdate()
'Wed, 05 May 2010 21:54:28 −0000'
>>> email.utils.formatdate(localtime=True)
'Wed, 05 May 2010 17:54:52 −0400'
>>> email.utils.formatdate(usegmt=True)
'Wed, 05 May 2010 21:55:22 GMT'
See the pymail and mailtools examples in this chapter for additional usage examples;
the latter is reused by the larger PyMailGUI and PyMailCGI email clients later in this
book.

Sending Email at the Interactive Prompt


So where are we in the Internet abstraction model now? With all this email fetching
and sending going on, it’s easy to lose the forest for the trees. Keep in mind that because
mail is transferred over sockets (remember sockets?), they are at the root of all this
activity. All email read and written ultimately consists of formatted bytes shipped over


SMTP: Sending Email | 919
Free download pdf