smtplibSMTP protocol clientSMTP协议客户端

Source code: Lib/smtplib.py


The smtplib module defines an SMTP client session object that can be used to send mail to any internet machine with an SMTP or ESMTP listener daemon. smtplib模块定义了一个SMTP客户端会话对象,可用于将邮件发送到任何具有SMTP或ESMTP侦听器守护程序的internet计算机。For details of SMTP and ESMTP operation, consult RFC 821 (Simple Mail Transfer Protocol) and RFC 1869 (SMTP Service Extensions).有关SMTP和ESMTP操作的详细信息,请参阅smtplib(简单邮件传输协议)和RFC 1869(SMTP服务扩展)。

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

An SMTP instance encapsulates an SMTP connection. SMTP实例封装SMTP连接。It has methods that support a full repertoire of SMTP and ESMTP operations. 它的方法支持SMTP和ESMTP操作的完整曲目。If the optional host and port parameters are given, the SMTP connect() method is called with those parameters during initialization. 如果给定了可选的主机和端口参数,则会在初始化期间使用这些参数调用SMTP connect()方法。If specified, local_hostname is used as the FQDN of the local host in the HELO/EHLO command. 如果指定,local_hostname将在HELO/EHLO命令中用作本地主机的FQDN。Otherwise, the local hostname is found using socket.getfqdn(). 否则,将使用socket.getfqdn()找到本地主机名。If the connect() call returns anything other than a success code, an SMTPConnectError is raised. 如果connect()调用返回成功代码以外的任何其他代码,则会引发SMTPConnectErrorThe optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). 可选的timeout参数指定阻塞操作(如连接尝试)的超时时间(以秒为单位)(如果未指定,将使用全局默认超时设置)。If the timeout expires, TimeoutError is raised. 如果超时过期,将引发TimeoutErrorThe optional source_address parameter allows binding to some specific source address in a machine with multiple network interfaces, and/or to some specific source TCP port. 可选的source_address参数允许绑定到具有多个网络接口的计算机中的特定源地址,和/或绑定到特定的源TCP端口。It takes a 2-tuple (host, port), for the socket to bind to as its source address before connecting. 它接受一个2元组(主机、端口),以便套接字在连接之前绑定到它的源地址。If omitted (or if host or port are '' and/or 0 respectively) the OS default behavior will be used.如果省略(或者主机或端口分别为''和/或0),将使用操作系统默认行为。

For normal use, you should only require the initialization/connect, sendmail(), and SMTP.quit() methods. 对于正常使用,您应该只需要initialization/connect、sendmail()SMTP.quit()方法。An example is included below.下面是一个例子。

The SMTP class supports the with statement. SMTP类支持with语句。When used like this, the SMTP QUIT command is issued automatically when the with statement exits. E.g.:这样使用时,当with语句退出时,会自动发出SMTP QUIT命令。如。:

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

All commands will raise an auditing event smtplib.SMTP.send with arguments self and data, where data is the bytes about to be sent to the remote host.所有命令都将引发审核事件smtplib.SMTP.send,其中参数为selfdata,其中data是即将发送到远程主机的字节。

Changed in version 3.3:版本3.3中更改: Support for the with statement was added.添加了对with语句的支持。

Changed in version 3.3:版本3.3中更改: source_address argument was added.添加了source_address参数。

New in version 3.5.版本3.5中新增。The SMTPUTF8 extension (RFC 6531) is now supported.现在支持SMTPUTF8扩展(RFC 6531)。

Changed in version 3.9:版本3.9中更改: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket如果timeout参数设置为零,它将引发ValueError以阻止创建非阻塞套接字

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

An SMTP_SSL instance behaves exactly the same as instances of SMTP. SMTP_SSL实例的行为与SMTP实例完全相同。SMTP_SSL should be used for situations where SSL is required from the beginning of the connection and using starttls() is not appropriate. 应该用于从连接开始就需要SSL并且不适合使用starttls()的情况。If host is not specified, the local host is used. 如果未指定host,则使用本地主机。If port is zero, the standard SMTP-over-SSL port (465) is used. 如果port为零,则使用标准SMTP over SSL端口(465)。The optional arguments local_hostname, timeout and source_address have the same meaning as they do in the SMTP class. 可选参数local_hostnametimeoutsource_address与它们在SMTP类中的含义相同。context, also optional, can contain a SSLContext and allows configuring various aspects of the secure connection. context(也是可选的)可以包含SSLContext,并允许配置安全连接的各个方面。Please read Security considerations for best practices.请阅读最佳实践的安全注意事项

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.keyfilecertfile是上下文的传统替代方法,可以指向用于SSL连接的PEM格式的私钥和证书链文件。

Changed in version 3.3:版本3.3中更改: context was added.添加了context

Changed in version 3.3:版本3.3中更改: source_address argument was added.添加了source_address参数。

Changed in version 3.4:版本3.4中更改: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).该类现在支持使用ssl.SSLContext.check_hostname服务器名称指示进行主机名检查(请参阅ssl.HAS_SNI)。

Deprecated since version 3.6: 自版本3.6起已弃用:keyfile and certfile are deprecated in favor of context. keyfilecertfile已被弃用,取而代之的是contextPlease use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.请改用ssl.SSLContext.load_cert_chain(),或让ssl.create_default_context()为您选择系统的受信任CA证书。

Changed in version 3.9:版本3.9中更改: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket如果timeout参数设置为零,它将引发ValueError以阻止创建非阻塞套接字

classsmtplib.LMTP(host='', port=LMTP_PORT, local_hostname=None, source_address=None[, timeout])

The LMTP protocol, which is very similar to ESMTP, is heavily based on the standard SMTP client. LMTP协议与ESMTP非常相似,它在很大程度上基于标准SMTP客户端。It’s common to use Unix sockets for LMTP, so our connect() method must support that as well as a regular host:port server. 为LMTP使用Unix套接字是很常见的,因此connect()方法必须支持它,以及常规的主机:端口服务器。The optional arguments local_hostname and source_address have the same meaning as they do in the SMTP class. 可选参数local_hostnamesource_address的含义与它们在SMTP类中的含义相同。To specify a Unix socket, you must use an absolute path for host, starting with a ‘/’.要指定Unix套接字,必须使用host的绝对路径,以“/”开头。

Authentication is supported, using the regular SMTP mechanism. 支持使用常规SMTP机制进行身份验证。When using a Unix socket, LMTP generally don’t support or require any authentication, but your mileage might vary.当使用Unix套接字时,LMTP通常不支持或不需要任何身份验证,但您的里程可能会有所不同。

Changed in version 3.9:版本3.9中更改: The optional timeout parameter was added.添加了可选的timeout参数。

A nice selection of exceptions is defined as well:此外,还定义了一系列异常:

exceptionsmtplib.SMTPException

Subclass of OSError that is the base exception class for all the other exceptions provided by this module.OSError的子类,它是此模块提供的所有其他异常的基本异常类。

Changed in version 3.4:版本3.4中更改: SMTPException became subclass of OSErrorOSError成为OSError的子类

exceptionsmtplib.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.当服务器意外断开连接,或在将SMTP实例连接到服务器之前尝试使用该实例时,会引发此异常。

exceptionsmtplib.SMTPResponseException

Base class for all exceptions that include an SMTP error code. 包含SMTP错误代码的所有异常的基类。These exceptions are generated in some instances when the SMTP server returns an error code. 在某些情况下,当SMTP服务器返回错误代码时,会生成这些异常。The error code is stored in the smtp_code attribute of the error, and the smtp_error attribute is set to the error message.错误代码存储在错误的smtp_code属性中,smtp_error属性设置为错误消息。

exceptionsmtplib.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.除了对所有SMTPResponseException异常设置的属性外,这还将“sender”设置为SMTP服务器拒绝的字符串。

exceptionsmtplib.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.每个收件人的错误都可以通过属性recipients进行访问,这是一个与SMTP.sendmail()返回的排序完全相同的字典。

exceptionsmtplib.SMTPDataError

The SMTP server refused to accept the message data.SMTP服务器拒绝接受邮件数据。

exceptionsmtplib.SMTPConnectError

Error occurred during establishment of a connection with the server.与服务器建立连接时出错。

exceptionsmtplib.SMTPHeloError

The server refused our HELO message.服务器拒绝了HELO消息。

exceptionsmtplib.SMTPNotSupportedError

The command or option attempted is not supported by the server.服务器不支持尝试的命令或选项。

New in version 3.5.版本3.5中新增。

exceptionsmtplib.SMTPAuthenticationError

SMTP authentication went wrong. SMTP身份验证出错。Most probably the server didn’t accept the username/password combination provided.很可能服务器不接受提供的用户名/密码组合。

See also

RFC 821 - Simple Mail Transfer Protocol简单邮件传输协议

Protocol definition for SMTP. SMTP的协议定义。This document covers the model, operating procedure, and protocol details for SMTP.本文档涵盖SMTP的模型、操作过程和协议详细信息。

RFC 1869 - SMTP Service ExtensionsSMTP服务扩展

Definition of the ESMTP extensions for SMTP. SMTP的ESMTP扩展的定义。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.这描述了一个使用新命令扩展SMTP的框架,支持动态发现服务器提供的命令,并定义了一些其他命令。

SMTP Objects对象

An SMTP instance has the following methods:SMTP实例具有以下方法:

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. level值为1或True将导致连接调试消息以及发送到服务器和从服务器接收的所有消息的调试消息。A value of 2 for level results in these messages being timestamped.级别值为2将导致这些消息带有时间戳。

Changed in version 3.5:版本3.5中更改: Added debuglevel 2.添加了调试级别2。

SMTP.docmd(cmd, args='')

Send a command cmd to the server. 向服务器发送命令cmdThe optional argument args is simply concatenated to the command, separated by a space.可选参数args简单地连接到命令,用空格分隔。

This returns a 2-tuple composed of a numeric response code and the actual response line (multiline responses are joined into one long line.)这将返回一个由数字响应代码和实际响应行组成的2元组(多行响应合并为一个长行)

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.如果在等待回复时与服务器的连接丢失,将引发SMTPServerDisconnected

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

Connect to a host on a given port. 连接到给定端口上的主机。The defaults are to connect to the local host at the standard SMTP port (25). 默认设置是通过标准SMTP端口(25)连接到本地主机。If the hostname ends with a colon (':') followed by a number, that suffix will be stripped off and the number interpreted as the port number to use. 如果主机名以冒号(':')结尾,后跟一个数字,则会去掉该后缀,并将该数字解释为要使用的端口号。This method is automatically invoked by the constructor if a host is specified during instantiation. 如果在实例化期间指定了主机,构造函数会自动调用此方法。Returns a 2-tuple of the response code and message sent by the server in its connection response.返回服务器在其连接响应中发送的响应代码和消息的二元组。

Raises an auditing event smtplib.connect with arguments self, host, port.使用参数selfhostport引发审核事件smtplib.connect

SMTP.helo(name='')

Identify yourself to the SMTP server using HELO. 使用HELO向SMTP服务器确认您的身份。The hostname argument defaults to the fully qualified domain name of the local host. hostname参数默认为本地主机的完全限定域名。The message returned by the server is stored as the helo_resp attribute of the object.服务器返回的消息存储为对象的helo_resp属性。

In normal operation it should not be necessary to call this method explicitly. 在正常操作中,不需要显式调用此方法。It will be implicitly called by the sendmail() when necessary.必要时,sendmail()将隐式调用它。

SMTP.ehlo(name='')

Identify yourself to an ESMTP server using EHLO. 使用EHLO向ESMTP服务器确认您的身份。The hostname argument defaults to the fully qualified domain name of the local host. hostname参数默认为本地主机的完全限定域名。Examine the response for ESMTP option and store them for use by has_extn(). 检查ESMTP选项的响应,并存储它们以供has_extn()使用。Also sets several informational attributes: the message returned by the server is stored as the ehlo_resp attribute, does_esmtp is set to True or False depending on whether the server supports ESMTP, and esmtp_features will be a dictionary containing the names of the SMTP service extensions this server supports, and their parameters (if any).还设置几个信息属性:服务器返回的消息存储为ehlo_resp属性,does_esmtp设置为TrueFalse,具体取决于服务器是否支持ESMTP,esmtp_features将是一个字典,其中包含此服务器支持的SMTP服务扩展名及其参数(如果有)。

Unless you wish to use has_extn() before sending mail, it should not be necessary to call this method explicitly. 除非您希望在发送邮件之前使用has_extn(),否则不必显式调用此方法。It will be implicitly called by sendmail() when necessary.必要时,sendmail()将隐式调用它。

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. 如果此会话中以前没有ehlo或helo命令,此方法将调用ehlo()和/或helo()It tries ESMTP EHLO first.它首先尝试ESMTP EHLO

SMTPHeloError

The server didn’t reply properly to the HELO greeting.服务器没有正确回复HELO问候语。

SMTP.has_extn(name)

Return True if name is in the set of SMTP service extensions returned by the server, False otherwise. 如果name位于服务器返回的SMTP服务扩展集中,则返回True,否则返回FalseCase is ignored.忽略大小写。

SMTP.verify(address)

Check the validity of an address on this server using SMTP VRFY. 使用SMTP VRFY检查此服务器上地址的有效性。Returns a tuple consisting of code 250 and a full RFC 822 address (including human name) if the user address is valid. 如果用户地址有效,则返回由代码250和完整RFC 822地址(包括人名)组成的元组。Otherwise returns an SMTP error code of 400 or greater and an error string.否则,将返回400或更大的SMTP错误代码和错误字符串。

Note

Many sites disable SMTP VRFY in order to foil spammers.许多网站禁用SMTP VRFY以阻止垃圾邮件发送者。

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

Log in on an SMTP server that requires authentication. 登录需要身份验证的SMTP服务器。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. 如果此会话中以前没有EHLOHELO命令,此方法将首先尝试ESMTP EHLOThis 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.服务器没有正确回复HELO问候语。

SMTPAuthenticationError

The server didn’t accept the username/password combination.服务器不接受用户名/密码组合。

SMTPNotSupportedError

The AUTH command is not supported by the server.服务器不支持AUTH命令。

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. 如果smtplib支持的每种身份验证方法被公布为服务器支持,则会依次尝试这些方法。See auth() for a list of supported authentication methods. 有关支持的身份验证方法的列表,请参阅auth()initial_response_ok is passed through to auth().initial_response_ok传递给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.可选关键字参数initial_response_ok指定,对于支持它的身份验证方法,RFC 4954中指定的“初始响应”是否可以与AUTH命令一起发送,而不需要质询/响应。

Changed in version 3.5:版本3.5中更改: SMTPNotSupportedError may be raised, and the initial_response_ok parameter was added.可能引发SMTPNotSupportedError,并添加了initial_response_ok参数。

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发出SMTP AUTH命令,并通过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.指定将哪个身份验证机制用作AUTH命令的参数;有效值列在esmtp_featuresauth元素中。

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. 如果可选关键字参数initial_response_oktrue,将首先调用authobject(),而不使用参数。It can return the RFC 4954 “initial response” ASCII str which will be encoded and sent with the AUTH command as below. 它可以返回RFC 4954“initial response”ASCII str,该字符串将使用AUTH命令进行编码并发送,如下所示。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. 如果authobject()不支持初始响应(例如,因为它需要质询),那么当使用challenge=None调用时,它应该返回NoneIf initial_response_ok is false, then authobject() will not be called first with None.如果initial_response_okfalse,则不会首先使用None调用authobject()

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. 如果初始响应检查返回None,或者initial_response_okfalse,将调用authobject()来处理服务器的质询响应;它传递的质询参数将是一个字节。It should return ASCII str data that will be base64 encoded and sent to the server.它应该返回将以base64编码并发送到服务器的ASCII strdata

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. SMTP类为CRAM-MD5PLAINLOGIN机制提供authobjects;它们分别命名为SMTP.auth_cram_md5SMTP.auth_plainSMTP.auth _loginThey all require that the user and password properties of the SMTP instance are set to appropriate values.它们都要求将SMTP实例的userpassword属性设置为适当的值。

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,而是可以调用login()方法,该方法将按列出的顺序依次尝试上述每个机制。auth is exposed to facilitate the implementation of authentication methods not (or not yet) supported directly by smtplib.公开以便于实现smtplib不直接支持(或尚未支持)的身份验证方法。

New in version 3.5.版本3.5中新增。

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

Put the SMTP connection in TLS (Transport Layer Security) mode. 将SMTP连接置于TLS(传输层安全)模式。All SMTP commands that follow will be encrypted. 随后的所有SMTP命令都将加密。You should then call ehlo() again.然后应再次调用ehlo()

If keyfile and certfile are provided, they are used to create an ssl.SSLContext.如果提供了keyfilecertfile,则它们用于创建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.可选context参数是ssl.SSLContext对象;这是使用keyfilecertfile的一种替代方法,如果指定了keyfilecertfiles,则两者都应为None

If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first.如果此会话中以前没有EHLOHELO命令,此方法将首先尝试ESMTP EHLO

Deprecated since version 3.6: 自版本3.6起已弃用:keyfile and certfile are deprecated in favor of context. keyfilecertfile已被弃用,取而代之的是contextPlease use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.请改用ssl.SSLContext.load_cert_chain(),或让ssl.create_default_context()为您选择系统的受信任CA证书。

SMTPHeloError

The server didn’t reply properly to the HELO greeting.服务器没有正确回复HELO问候语。

SMTPNotSupportedError

The server does not support the STARTTLS extension.服务器不支持STARTTLS扩展。

RuntimeError

SSL/TLS support is not available to your Python interpreter.Python解释器不支持SSL/TLS。

Changed in version 3.3:版本3.3中更改: context was added.添加了context

Changed in version 3.4:版本3.4中更改: The method now supports hostname check with SSLContext.check_hostname and Server Name Indicator (see HAS_SNI).该方法现在支持使用SSLContext.check_hostname服务器名称指示符进行主机名检查(请参阅HAS_SNI)。

Changed in version 3.5:版本3.5中更改: The error raised for lack of STARTTLS support is now the SMTPNotSupportedError subclass instead of the base SMTPException.由于缺少STARTTLS支持而引发的错误现在是SMTPNotSupportedError子类,而不是基本的SMTPException

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

Send mail. 发送邮件。The required arguments are an RFC 822 from-address string, a list of RFC 822 to-address strings (a bare string will be treated as a list with 1 address), and a message string. 所需的参数包括RFC 822from-address字符串、RFC 822to-address字符串列表(裸字符串将被视为具有1个地址的列表)和消息字符串。The caller may pass a list of ESMTP options (such as 8bitmime) to be used in MAIL FROM commands as mail_options. 调用者可以将要在MAIL FROM命令中使用的ESMTP选项列表(如8bitmime)作为mail_options传递。ESMTP options (such as DSN commands) that should be used with all RCPT commands can be passed as rcpt_options. 应与所有RCPT命令一起使用的ESMTP选项(例如DSN命令)可以作为rcpt_options传递。(If you need to use different ESMTP options to different recipients you have to use the low-level methods such as mail(), rcpt() and data() to send the message.)(如果需要对不同的收件人使用不同的ESMTP选项,则必须使用低级方法,如mail()rcpt()data()来发送消息。)

Note

The from_addr and to_addrs parameters are used to construct the message envelope used by the transport agents. from_addrto_addrs参数用于构造传输代理使用的消息信封。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. msg可以是包含ASCII范围内字符的字符串,也可以是字节字符串。A string is encoded to bytes using the ascii codec, and lone \r and \n characters are converted to \r\n characters. 字符串使用ascii编解码器编码为字节,孤立字符\r\n字符转换为字符\r\nA byte string is not modified.字节字符串未修改。

If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. 如果此会话中以前没有EHLOHELO命令,此方法将首先尝试ESMTP EHLOIf 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). 如果服务器执行ESMTP,消息大小和每个指定的选项都将传递给它(如果该选项位于服务器公布的功能集中)。If EHLO fails, HELO will be tried and ESMTP options suppressed.如果EHLO失败,将尝试HELO并取消ESMTP选项。

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.每个条目都包含SMTP错误代码元组和服务器发送的附带错误消息。

If SMTPUTF8 is included in mail_options, and the server supports it, from_addr and to_addrs may contain non-ASCII characters.如果mail_options中包含SMTPUTF8,并且服务器支持它,那么from_addrto_addrs可能包含非ASCII字符。

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).异常对象的recipients属性是一个字典,其中包含有关被拒绝的收件人的信息(如至少接受一个收件人时返回的信息)。

SMTPHeloError

The server didn’t reply properly to the HELO greeting.服务器没有正确回复HELO问候语。

SMTPSenderRefused

The server didn’t accept the from_addr.服务器不接受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.mail_options中提供了SMTPUTF8,但服务器不支持。

Unless otherwise noted, the connection will be open even after an exception is raised.除非另有说明,否则即使引发异常,连接也将打开。

Changed in version 3.2:版本3.2中更改: msg may be a byte string.

Changed in version 3.5:版本3.5中更改: SMTPUTF8 support added, and SMTPNotSupportedError may be raised if SMTPUTF8 is specified but the server does not support it.添加了SMTPUTF8支持,如果指定了SMTPUTF8,但服务器不支持它,则可能引发SMTPNotSupportedError

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

This is a convenience method for calling sendmail() with the message represented by an email.message.Message object. 这是使用email.message.Message对象表示的消息调用sendmail()的方便方法。The arguments have the same meaning as for sendmail(), except that msg is a Message object.这些参数与sendmail()的含义相同,只是msg是一个Message对象。

If from_addr is None or to_addrs is None, send_message fills those arguments with addresses extracted from the headers of msg as specified in RFC 5322: from_addr is set to the Sender field if it is present, and otherwise to the From field. 如果from_addrNoneto_addrsNone,则send_message使用从msg头提取的地址填充这些参数,如RFC 5322中所述:如果存在from_addr,则将其设置为Sender字段,否则设置为from字段。to_addrs combines the values (if any) of the To, Cc, and Bcc fields from msg. to_addrs组合消息中“收件人”、“抄送”和“密件抄送”字段的值(如果有)。If exactly one set of Resent-* headers appear in the message, the regular headers are ignored and the Resent-* headers are used instead. 如果消息中只出现一组Resent-*标头,则会忽略常规标头,而使用Resent-x标头。If the message contains more than one set of Resent-* headers, a ValueError is raised, since there is no way to unambiguously detect the most recent set of Resent- headers.如果消息包含多组Resent-*头,则会引发ValueError,因为无法明确检测最新的Resent-标头集。

send_message serializes msg using BytesGenerator with \r\n as the linesep, and calls sendmail() to transmit the resulting message. send_message使用BytesGenerator配合\r\nmsg序列化为linesep,并调用sendmail()来传输生成的消息。Regardless of the values of from_addr and to_addrs, send_message does not transmit any Bcc or Resent-Bcc headers that may appear in msg. 无论from_addrto_addrs的值是多少,send_message都不会传输消息中可能出现的任何密件抄送或重新发送密件抄收头。If any of the addresses in from_addr and to_addrs contain non-ASCII characters and the server does not advertise SMTPUTF8 support, an SMTPNotSupported error is raised. 如果from_addrto_addr中的任何地址包含非ASCII字符,并且服务器不公布SMTPUTF8支持,则会引发SMTPNotSupported错误。Otherwise the Message is serialized with a clone of its policy with the utf8 attribute set to True, and SMTPUTF8 and BODY=8BITMIME are added to mail_options.否则,将使用其policy的克隆(utf8属性设置为True)对Message进行序列化,并将SMTPUTF8BODY=8BITMIME添加到mail_options

New in version 3.2.版本3.2中新增。

New in version 3.5.版本3.5中新增。Support for internationalized addresses (SMTPUTF8).支持国际化地址(SMTPUTF8)。

SMTP.quit()

Terminate the SMTP session and close the connection. 终止SMTP会话并关闭连接。Return the result of the SMTP QUIT command.返回SMTP QUIT命令的结果。

Low-level methods corresponding to the standard SMTP/ESMTP commands HELP, RSET, NOOP, MAIL, RCPT, and DATA are also supported. 还支持对应于标准SMTP/ESMTP命令HELPRSETNOOPMAILRCPTDATA的低级方法。Normally these do not need to be called directly, so they are not documented here. 通常不需要直接调用这些函数,因此这里不记录它们。For details, consult the module code.有关详细信息,请参阅模块代码。

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. 请注意,要包含在消息中的标题必须包含在输入的消息中;此示例不处理RFC 822标头。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()

Note

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: Examples.通常,您会希望使用email包的功能构建电子邮件消息,然后可以通过send_message()发送该消息;请参阅电子邮件:示例