21.17. "smtplib" ---SMTP协议客户端
**********************************

**源代码：** Lib/smtplib.py

======================================================================

"smtplib" 模块定义了一个 SMTP 客户端会话对象，该对象可将邮件发送到
Internet 上带有 SMTP 或 ESMTP 接收程序的计算机。 关于 SMTP 和 ESMTP 操
作的详情请参阅 **RFC 821** (简单邮件传输协议) 和 **RFC 1869** (SMTP 服
务扩展)。

class smtplib.SMTP(host='', port=0, local_hostname=None[, timeout], source_address=None)

   一个 "SMTP" 实例就是一个封装好的 SMTP 连接。该实例具有的方法支持所
   有 SMTP 和 ESMTP 操作。如果传入了可选参数 host 和 port，那么将在初
   始化时使用这些参数调用 SMTP "connect()" 方法。如果传入了
   *local_hostname*，它将在 HELO/EHLO 命令中被用作本地主机的 FQDN。否
   则将使用 "socket.getfqdn()" 找到本地主机名。如果 "connect()" 返回了
   成功码以外的内容，则引发 "SMTPConnectError" 异常。可选参数
   *timeout* 指定阻塞操作（如连接尝试）的超时（以秒为单位，如果未指定
   超时，将使用全局默认超时设置）。到达超时时长后会引发
   "socket.timeout" 异常。可选参数 source_address 允许在有多张网卡的计
   算机中绑定到某些特定的源地址，和/或绑定到某些特定的源 TCP 端口。在
   连接前，套接字需要绑定一个 2 元组 (host, port) 作为其源地址。如果省
   略，或者是主机为 "''" 和/或端口为 0，则将使用操作系统默认行为。

   正常使用时，只需要初始化或 connect 方法，"sendmail()" 方法，再加上
   "SMTP.quit()" 方法即可。下文包括了一个示例。

   The "SMTP" class supports the "with" statement.  When used like
   this, the SMTP "QUIT" command is issued automatically when the
   "with" statement exits.  E.g.:

      >>> from smtplib import SMTP
      >>> with SMTP("domain.org") as smtp:
      ...     smtp.noop()
      ...
      (250, b'Ok')
      >>>

   在 3.3 版更改: 支持了 "with" 语句。

   在 3.3 版更改: source_address argument was added.

   3.5 新版功能: The SMTPUTF8 extension (**RFC 6531**) is now
   supported.

class smtplib.SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, certfile=None[, timeout], context=None, source_address=None)

   "SMTP_SSL" 实例与 "SMTP" 实例的行为完全相同。在开始连接就需要 SSL，
   且 "starttls()" 不适合的情况下，应该使用 "SMTP_SSL"。如果未指定
   *host*，则使用 localhost。如果 *port* 为 0，则使用标准 SMTP-over-
   SSL 端口（465）。可选参数 *local_hostname*、*timeout* 和
   *source_address* 的含义与 "SMTP" 类中的相同。可选参数 *context* 是
   一个 "SSLContext" 对象，可以从多个方面配置安全连接。请阅读 安全考量
   以获取最佳实践。

   *keyfile* and *certfile* are a legacy alternative to *context*, and
   can point to a PEM formatted private key and certificate chain file
   for the SSL connection.

   在 3.3 版更改: 增加了 *context*。

   在 3.3 版更改: source_address argument was added.

   在 3.4 版更改: 本类现在支持通过 "ssl.SSLContext.check_hostname" 和
   *服务器名称提示* （参阅 "ssl.HAS_SNI"）进行主机名检查。

   3.6 版后已移除: *keyfile* 和 *certfile* 已弃用并转而推荐 *context*
   。 请改用 "ssl.SSLContext.load_cert_chain()" 或让
   "ssl.create_default_context()" 为你选择系统所信任的 CA 证书。

class smtplib.LMTP(host='', port=LMTP_PORT, local_hostname=None, source_address=None)

   LMTP 协议与 ESMTP 非常相似，它很大程度上基于标准的 SMTP 客户端。将
   Unix 套接字用于 LMTP 是很常见的，因此 "connect()" 方法支持 Unix 套
   接字，也支持常规的 host:port 服务器。可选参数 local_hostname 和
   source_address 的含义与 "SMTP" 类中的相同。要指定 Unix 套接字，
   *host* 必须使用绝对路径，以 '/' 开头。

   Authentication is supported, using the regular SMTP mechanism. When
   using a Unix socket, LMTP generally don't support or require any
   authentication, but your mileage might vary.

A nice selection of exceptions is defined as well:

exception smtplib.SMTPException

   Subclass of "OSError" that is the base exception class for all the
   other exceptions provided by this module.

   在 3.4 版更改: SMTPException became subclass of "OSError"

exception smtplib.SMTPServerDisconnected

   This exception is raised when the server unexpectedly disconnects,
   or when an attempt is made to use the "SMTP" instance before
   connecting it to a server.

exception smtplib.SMTPResponseException

   Base class for all exceptions that include an SMTP error code.
   These exceptions are generated in some instances when the SMTP
   server returns an error code.  The error code is stored in the
   "smtp_code" attribute of the error, and the "smtp_error" attribute
   is set to the error message.

exception smtplib.SMTPSenderRefused

   Sender address refused.  In addition to the attributes set by on
   all "SMTPResponseException" exceptions, this sets 'sender' to the
   string that the SMTP server refused.

exception smtplib.SMTPRecipientsRefused

   All recipient addresses refused.  The errors for each recipient are
   accessible through the attribute "recipients", which is a
   dictionary of exactly the same sort as "SMTP.sendmail()" returns.

exception smtplib.SMTPDataError

   The SMTP server refused to accept the message data.

exception smtplib.SMTPConnectError

   Error occurred during establishment of a connection  with the
   server.

exception smtplib.SMTPHeloError

   The server refused our "HELO" message.

exception smtplib.SMTPNotSupportedError

   The command or option attempted is not supported by the server.

   3.5 新版功能.

exception smtplib.SMTPAuthenticationError

   SMTP authentication went wrong.  Most probably the server didn't
   accept the username/password combination provided.

参见:

  **RFC 821** - Simple Mail Transfer Protocol
     Protocol definition for SMTP.  This document covers the model,
     operating procedure, and protocol details for SMTP.

  **RFC 1869** - SMTP Service Extensions
     Definition of the ESMTP extensions for SMTP.  This describes a
     framework for extending SMTP with new commands, supporting
     dynamic discovery of the commands provided by the server, and
     defines a few additional commands.


21.17.1. SMTP Objects
=====================

An "SMTP" instance has the following methods:

SMTP.set_debuglevel(level)

   Set the debug output level.  A value of 1 or "True" for *level*
   results in debug messages for connection and for all messages sent
   to and received from the server.  A value of 2 for *level* results
   in these messages being timestamped.

   在 3.5 版更改: Added debuglevel 2.

SMTP.docmd(cmd, args='')

   Send a command *cmd* to the server.  The optional argument *args*
   is simply concatenated to the command, separated by a space.

   This returns a 2-tuple composed of a numeric response code and the
   actual response line (multiline responses are joined into one long
   line.)

   In normal operation it should not be necessary to call this method
   explicitly. It is used to implement other methods and may be useful
   for testing private extensions.

   If the connection to the server is lost while waiting for the
   reply, "SMTPServerDisconnected" will be raised.

SMTP.connect(host='localhost', port=0)

   连接到某个主机的某个端口。默认是连接到 localhost 的标准 SMTP 端口（
   25）上。如果主机名以冒号 ("':'") 结尾，后跟数字，则该后缀将被删除，
   且数字将视作要使用的端口号。如果在实例化时指定了 host，则构造函数会
   自动调用本方法。返回包含响应码和响应消息的 2 元组，它们由服务器在其
   连接响应中发送。

SMTP.helo(name='')

   Identify yourself to the SMTP server using "HELO".  The hostname
   argument defaults to the fully qualified domain name of the local
   host. The message returned by the server is stored as the
   "helo_resp" attribute of the object.

   In normal operation it should not be necessary to call this method
   explicitly. It will be implicitly called by the "sendmail()" when
   necessary.

SMTP.ehlo(name='')

   使用 "EHLO" 向 ESMTP 服务器标识自身。hostname 参数默认为 localhost
   的标准域名。使用 "has_extn()" 来检查响应中的 ESMTP 选项，并将它们保
   存起来。还给一些信息性的属性赋值：服务器返回的消息存储为
   "ehlo_resp" 属性；根据服务器是否支持 ESMTP，将 "does_esmtp" 设置为
   true 或 false；而 "esmtp_features" 是一个字典，包含该服务器支持的
   SMTP 服务扩展的名称及参数（如果有参数）。

   Unless you wish to use "has_extn()" before sending mail, it should
   not be necessary to call this method explicitly.  It will be
   implicitly called by "sendmail()" when necessary.

SMTP.ehlo_or_helo_if_needed()

   This method calls "ehlo()" and/or "helo()" if there has been no
   previous "EHLO" or "HELO" command this session.  It tries ESMTP
   "EHLO" first.

   "SMTPHeloError"
      The server didn't reply properly to the "HELO" greeting.

SMTP.has_extn(name)

   Return "True" if *name* is in the set of SMTP service extensions
   returned by the server, "False" otherwise. Case is ignored.

SMTP.verify(address)

   Check the validity of an address on this server using SMTP "VRFY".
   Returns a tuple consisting of code 250 and a full **RFC 822**
   address (including human name) if the user address is valid.
   Otherwise returns an SMTP error code of 400 or greater and an error
   string.

   注解:

     Many sites disable SMTP "VRFY" in order to foil spammers.

SMTP.login(user, password, *, initial_response_ok=True)

   Log in on an SMTP server that requires authentication. The
   arguments are the username and the password to authenticate with.
   If there has been no previous "EHLO" or "HELO" command this
   session, this method tries ESMTP "EHLO" first. This method will
   return normally if the authentication was successful, or may raise
   the following exceptions:

   "SMTPHeloError"
      The server didn't reply properly to the "HELO" greeting.

   "SMTPAuthenticationError"
      The server didn't accept the username/password combination.

   "SMTPNotSupportedError"
      The "AUTH" command is not supported by the server.

   "SMTPException"
      No suitable authentication method was found.

   Each of the authentication methods supported by "smtplib" are tried
   in turn if they are advertised as supported by the server.  See
   "auth()" for a list of supported authentication methods.
   *initial_response_ok* is passed through to "auth()".

   Optional keyword argument *initial_response_ok* specifies whether,
   for authentication methods that support it, an "initial response"
   as specified in **RFC 4954** can be sent along with the "AUTH"
   command, rather than requiring a challenge/response.

   在 3.5 版更改: "SMTPNotSupportedError" may be raised, and the
   *initial_response_ok* parameter was added.

SMTP.auth(mechanism, authobject, *, initial_response_ok=True)

   Issue an "SMTP" "AUTH" command for the specified authentication
   *mechanism*, and handle the challenge response via *authobject*.

   *mechanism* specifies which authentication mechanism is to be used
   as argument to the "AUTH" command; the valid values are those
   listed in the "auth" element of "esmtp_features".

   *authobject* must be a callable object taking an optional single
   argument:

      data = authobject(challenge=None)

   If optional keyword argument *initial_response_ok* is true,
   "authobject()" will be called first with no argument.  It can
   return the **RFC 4954** "initial response" ASCII "str" which will
   be encoded and sent with the "AUTH" command as below.  If the
   "authobject()" does not support an initial response (e.g. because
   it requires a challenge), it should return "None" when called with
   "challenge=None".  If *initial_response_ok* is false, then
   "authobject()" will not be called first with "None".

   If the initial response check returns "None", or if
   *initial_response_ok* is false, "authobject()" will be called to
   process the server's challenge response; the *challenge* argument
   it is passed will be a "bytes".  It should return ASCII "str"
   *data* that will be base64 encoded and sent to the server.

   The "SMTP" class provides "authobjects" for the "CRAM-MD5",
   "PLAIN", and "LOGIN" mechanisms; they are named
   "SMTP.auth_cram_md5", "SMTP.auth_plain", and "SMTP.auth_login"
   respectively.  They all require that the "user" and "password"
   properties of the "SMTP" instance are set to appropriate values.

   User code does not normally need to call "auth" directly, but can
   instead call the "login()" method, which will try each of the above
   mechanisms in turn, in the order listed.  "auth" is exposed to
   facilitate the implementation of authentication methods not (or not
   yet) supported directly by "smtplib".

   3.5 新版功能.

SMTP.starttls(keyfile=None, certfile=None, context=None)

   Put the SMTP connection in TLS (Transport Layer Security) mode.
   All SMTP commands that follow will be encrypted.  You should then
   call "ehlo()" again.

   If *keyfile* and *certfile* are provided, they are used to create
   an "ssl.SSLContext".

   Optional *context* parameter is an "ssl.SSLContext" object; This is
   an alternative to using a keyfile and a certfile and if specified
   both *keyfile* and *certfile* should be "None".

   If there has been no previous "EHLO" or "HELO" command this
   session, this method tries ESMTP "EHLO" first.

   3.6 版后已移除: *keyfile* 和 *certfile* 已弃用并转而推荐 *context*
   。 请改用 "ssl.SSLContext.load_cert_chain()" 或让
   "ssl.create_default_context()" 为你选择系统所信任的 CA 证书。

   "SMTPHeloError"
      The server didn't reply properly to the "HELO" greeting.

   "SMTPNotSupportedError"
      The server does not support the STARTTLS extension.

   "RuntimeError"
      SSL/TLS support is not available to your Python interpreter.

   在 3.3 版更改: 增加了 *context*。

   在 3.4 版更改: The method now supports hostname check with
   "SSLContext.check_hostname" and *Server Name Indicator* (see
   "HAS_SNI").

   在 3.5 版更改: The error raised for lack of STARTTLS support is now
   the "SMTPNotSupportedError" subclass instead of the base
   "SMTPException".

SMTP.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())

   发送邮件。必要参数是一个 **RFC 822** 发件地址字符串，一个 **RFC
   822** 收件地址字符串列表（裸字符串将被视为含有 1 个地址的列表），以
   及一个消息字符串。调用者可以将 ESMTP 选项列表（如 "8bitmime"）作为
   *mail_options* 传入，用于 "MAIL FROM" 命令。需要与所有 "RCPT" 命令
   一起使用的 ESMTP 选项（如 "DSN" 命令）可以作为 *rcpt_options* 传入
   。（如果需要对不同的收件人使用不同的 ESMTP 选项，则必须使用底层的方
   法来发送消息，如 "mail()", "rcpt()" 和 "data()"。）

   注解:

     The *from_addr* and *to_addrs* parameters are used to construct
     the message envelope used by the transport agents.  "sendmail"
     does not modify the message headers in any way.

   *msg* may be a string containing characters in the ASCII range, or
   a byte string.  A string is encoded to bytes using the ascii codec,
   and lone "\r" and "\n" characters are converted to "\r\n"
   characters.  A byte string is not modified.

   If there has been no previous "EHLO" or "HELO" command this
   session, this method tries ESMTP "EHLO" first. If the server does
   ESMTP, message size and each of the specified options will be
   passed to it (if the option is in the feature set the server
   advertises).  If "EHLO" fails, "HELO" will be tried and ESMTP
   options suppressed.

   This method will return normally if the mail is accepted for at
   least one recipient. Otherwise it will raise an exception.  That
   is, if this method does not raise an exception, then someone should
   get your mail. If this method does not raise an exception, it
   returns a dictionary, with one entry for each recipient that was
   refused.  Each entry contains a tuple of the SMTP error code and
   the accompanying error message sent by the server.

   If "SMTPUTF8" is included in *mail_options*, and the server
   supports it, *from_addr* and *to_addrs* may contain non-ASCII
   characters.

   This method may raise the following exceptions:

   "SMTPRecipientsRefused"
      All recipients were refused.  Nobody got the mail.  The
      "recipients" attribute of the exception object is a dictionary
      with information about the refused recipients (like the one
      returned when at least one recipient was accepted).

   "SMTPHeloError"
      The server didn't reply properly to the "HELO" greeting.

   "SMTPSenderRefused"
      The server didn't accept the *from_addr*.

   "SMTPDataError"
      The server replied with an unexpected error code (other than a
      refusal of a recipient).

   "SMTPNotSupportedError"
      "SMTPUTF8" was given in the *mail_options* but is not supported
      by the server.

   Unless otherwise noted, the connection will be open even after an
   exception is raised.

   在 3.2 版更改: *msg* may be a byte string.

   在 3.5 版更改: "SMTPUTF8" support added, and
   "SMTPNotSupportedError" may be raised if "SMTPUTF8" is specified
   but the server does not support it.

SMTP.send_message(msg, from_addr=None, to_addrs=None, mail_options=(), rcpt_options=())

   本方法是一种快捷方法，用于带着消息调用 "sendmail()"，消息由
   "email.message.Message" 对象表示。参数的含义与 "sendmail()" 中的相
   同，除了 *msg*，它是一个 "Message" 对象。

   如果 *from_addr* 为 "None" 或 *to_addrs* 为 "None"，那么
   ``send_message``将根据 **RFC 5322**，从 *msg* 头部提取地址填充下列
   参数：如果头部存在 *Sender* 字段，则用它填充 *from_addr*，不存在则
   用 *From* 字段填充 *from_addr*。*to_addrs* 组合了 *msg* 中的 *To*,
   *Cc* 和 *Bcc* 字段的值（字段存在的情况下）。如果一组 *Resent-** 头
   部恰好出现在 message 中，那么就忽略常规的头部，改用 *Resent-** 头部
   。如果 message 包含多组 *Resent-** 头部，则引发 "ValueError"，因为
   无法明确检测出哪一组 *Resent-* 头部是最新的。

   "send_message" 使用 "BytesGenerator" 来序列化 *msg*，且将 "\r\n" 作
   为 *linesep*，并调用 "sendmail()" 来传输序列化后的结果。无论
   *from_addr* 和 *to_addrs* 的值为何，"send_message" 都不会传输 *msg*
   中可能出现的 *Bcc* 或 *Resent-Bcc* 头部。如果 *from_addr* 和
   *to_addrs* 中的某个地址包含非 ASCII 字符，且服务器没有声明支持
   "SMTPUTF8"，则引发 "SMTPNotSupported" 错误。如果服务器支持，则
   "Message" 将按新克隆的 "policy" 进行序列化，其中的 "utf8" 属性被设
   置为 "True"，且 "SMTPUTF8" 和 "BODY=8BITMIME" 被添加到
   *mail_options* 中。

   3.2 新版功能.

   3.5 新版功能: Support for internationalized addresses ("SMTPUTF8").

SMTP.quit()

   Terminate the SMTP session and close the connection.  Return the
   result of the SMTP "QUIT" command.

Low-level methods corresponding to the standard SMTP/ESMTP commands
"HELP", "RSET", "NOOP", "MAIL", "RCPT", and "DATA" are also supported.
Normally these do not need to be called directly, so they are not
documented here.  For details, consult the module code.


21.17.2. SMTP Example
=====================

This example prompts the user for addresses needed in the message
envelope ('To' and 'From' addresses), and the message to be delivered.
Note that the headers to be included with the message must be included
in the message as entered; this example doesn't do any processing of
the **RFC 822** headers.  In particular, the 'To' and 'From' addresses
must be included in the message headers explicitly.

   import smtplib

   def prompt(prompt):
       return input(prompt).strip()

   fromaddr = prompt("From: ")
   toaddrs  = prompt("To: ").split()
   print("Enter message, end with ^D (Unix) or ^Z (Windows):")

   # Add the From: and To: headers at the start!
   msg = ("From: %s\r\nTo: %s\r\n\r\n"
          % (fromaddr, ", ".join(toaddrs)))
   while True:
       try:
           line = input()
       except EOFError:
           break
       if not line:
           break
       msg = msg + line

   print("Message length is", len(msg))

   server = smtplib.SMTP('localhost')
   server.set_debuglevel(1)
   server.sendmail(fromaddr, toaddrs, msg)
   server.quit()

注解:

  In general, you will want to use the "email" package's features to
  construct an email message, which you can then send via
  "send_message()"; see email: 示例.
