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

(yzsuai) #1
to the SMTP server via a socket when the call returns. Technically, the connect
method establishes connection to a server, but the SMTP object calls this method
automatically if the mail server name is passed in this way.

failed = server.sendmail(From, Tos, text)
Call the SMTP object’s sendmail method, passing in the sender address, one or
more recipient addresses, and the raw text of the message itself with as many
standard mail header lines as you care to provide.


When you’re done, be sure to call the object’s quit method to disconnect from the
server and finalize the transaction. Notice that, on failure, the sendmail method may
either raise an exception or return a list of the recipient addresses that failed; the script
handles the latter case itself but lets exceptions kill the script with a Python error
message.


Subtly, calling the server object’s quit method after sendmail raises an exception may
or may not work as expected—quit can actually hang until a server timeout if the send
fails internally and leaves the interface in an unexpected state. For instance, this can
occur on Unicode encoding errors when translating the outgoing mail to bytes per the
ASCII scheme (the rset reset request hangs in this case, too). An alternative close
method simply closes the client’s sockets without attempting to send a quit command
to the server; quit calls close internally as a last step (assuming the quit command can
be sent!).


For advanced usage, SMTP objects provide additional calls not used in this example:



  • server.login(user, password) provides an interface to SMTP servers that require
    and support authentication; watch for this call to appear as an option in the mail
    tools package example later in this chapter.

  • server.starttls([keyfile[, certfile]]) puts the SMTP connection in Transport
    Layer Security (TLS) mode; all commands will be encrypted using the Python
    ssl module’s socket wrapper SSL support, and they assume the server supports
    this mode.


See the Python library manual for more on these and other calls not covered here.


Sending Messages


Let’s ship a few messages across the world. The smtpmail script is a one-shot tool: each
run allows you to send a single new mail message. Like most of the client-side tools in
this chapter, it can be run from any computer with Python and an Internet link that
supports SMTP (most do, though some public access machines may restrict users to
HTTP [Web] access only or require special server SMTP configuration). Here it is run-
ning on Windows:


C:\...\PP4E\Internet\Email> smtpmail.py
From? [email protected]
To? [email protected]

SMTP: Sending Email | 913
Free download pdf