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

(yzsuai) #1

import smtplib, sys, email.utils, mailconfig
mailserver = mailconfig.smtpservername # ex: smtp.rmi.net


From = input('From? ').strip() # or import from mailconfig
To = input('To? ').strip() # ex: [email protected]
Tos = To.split(';') # allow a list of recipients
Subj = input('Subj? ').strip()
Date = email.utils.formatdate() # curr datetime, rfc2822


standard headers, followed by blank line, followed by text


text = ('From: %s\nTo: %s\nDate: %s\nSubject: %s\n\n' % (From, To, Date, Subj))


print('Type message text, end with line=[Ctrl+d (Unix), Ctrl+z (Windows)]')
while True:
line = sys.stdin.readline()
if not line:
break # exit on ctrl-d/z
#if line[:4] == 'From':


line = '>' + line # servers may escape


text += line


print('Connecting...')
server = smtplib.SMTP(mailserver) # connect, no log-in step
failed = server.sendmail(From, Tos, text)
server.quit()
if failed: # smtplib may raise exceptions
print('Failed recipients:', failed) # too, but let them pass here
else:
print('No errors.')
print('Bye.')


Most of this script is user interface—it inputs the sender’s address (From), one or more
recipient addresses (To, separated by “;” if more than one), and a subject line. The
sending date is picked up from Python’s standard time module, standard header lines
are formatted, and the while loop reads message lines until the user types the end-of-
file character (Ctrl-Z on Windows, Ctrl-D on Linux).


To be robust, be sure to add a blank line between the header lines and the body in the
message’s text; it’s required by the SMTP protocol and some SMTP servers enforce
this. Our script conforms by inserting an empty line with \n\n at the end of the string
format expression—one \n to terminate the current line and another for a blank line;
smtplib expands \n to Internet-style \r\n internally prior to transmission, so the short
form is fine here. Later in this chapter, we’ll format our messages with the Python
email package, which handles such details for us automatically.


The rest of the script is where all the SMTP magic occurs: to send a mail by SMTP,
simply run these two sorts of calls:


server = smtplib.SMTP(mailserver)
Make an instance of the SMTP object, passing in the name of the SMTP server that
will dispatch the message first. If this doesn’t throw an exception, you’re connected


912 | Chapter 13: Client-Side Scripting

Free download pdf