smtplib
— SMTP 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服务扩展)。
-
class
smtplib.
SMTP
(host='', port=0, local_hostname=None, [timeout, ]source_address=None)¶ AnSMTP
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如果给定了可选的主机和端口参数,则会在初始化期间使用这些参数调用SMTPconnect()
method is called with those parameters during initialization.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, anSMTPConnectError
is raised.connect()
调用返回成功代码以外的任何其他代码,则会引发SMTPConnectError
。The 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.TimeoutError
。The 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,对于正常使用,您应该只需要initialization/connect、sendmail()
, andSMTP.quit()
methods.sendmail()
和SMTP.quit()
方法。An example is included below.下面是一个例子。TheSMTP
class supports thewith
statement.SMTP
类支持with
语句。When used like this, the SMTP这样使用时,当QUIT
command is issued automatically when thewith
statement exits. E.g.:with
语句退出时,会自动发出SMTPQUIT
命令。如。:>>> 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 argumentsself
anddata
, wheredata
is the bytes about to be sent to the remote host.smtplib.SMTP.send
,其中参数为self
和data
,其中data
是即将发送到远程主机的字节。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如果timeout参数设置为零,它将引发ValueError
to prevent the creation of a non-blocking socketValueError
以阻止创建非阻塞套接字
-
class
smtplib.
SMTP_SSL
(host='', port=0, local_hostname=None, keyfile=None, certfile=None, [timeout, ]context=None, source_address=None)¶ AnSMTP_SSL
instance behaves exactly the same as instances ofSMTP
.SMTP_SSL
实例的行为与SMTP
实例完全相同。SMTP_SSL
should be used for situations where SSL is required from the beginning of the connection and using应该用于从连接开始就需要SSL并且不适合使用starttls()
is not appropriate.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可选参数local_hostname、timeout和source_address与它们在SMTP类中的含义相同。SMTP
class.context, also optional, can contain acontext(也是可选的)可以包含SSLContext
and allows configuring various aspects of the secure connection.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.keyfile和certfile是上下文的传统替代方法,可以指向用于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 (seessl.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.keyfile和certfile已被弃用,取而代之的是context。Please use请改用ssl.SSLContext.load_cert_chain()
instead, or letssl.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如果timeout参数设置为零,它将引发ValueError
to prevent the creation of a non-blocking socketValueError
以阻止创建非阻塞套接字
-
class
smtplib.
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为LMTP使用Unix套接字是很常见的,因此connect()
method must support that as well as a regular host:port server.connect()
方法必须支持它,以及常规的主机:端口服务器。The optional arguments local_hostname and source_address have the same meaning as they do in the可选参数local_hostname和source_address的含义与它们在SMTP
class.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:此外,还定义了一系列异常:
-
exception
smtplib.
SMTPException
¶ Subclass ofOSError
that is the base exception class for all the other exceptions provided by this module.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.SMTP
实例连接到服务器之前尝试使用该实例时,会引发此异常。
-
exception
smtplib.
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 thesmtp_error
attribute is set to the error message.smtp_code
属性中,smtp_error
属性设置为错误消息。
-
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.SMTPResponseException
异常设置的属性外,这还将“sender”设置为SMTP服务器拒绝的字符串。
-
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 asSMTP.sendmail()
returns.recipients
进行访问,这是一个与SMTP.sendmail()
返回的排序完全相同的字典。
-
exception
smtplib.
SMTPDataError
¶ The SMTP server refused to accept the message data.SMTP服务器拒绝接受邮件数据。
-
exception
smtplib.
SMTPConnectError
¶ Error occurred during establishment of a connection with the server.与服务器建立连接时出错。
-
exception
smtplib.
SMTPHeloError
¶ The server refused our服务器拒绝了HELO
message.HELO
消息。
-
exception
smtplib.
SMTPNotSupportedError
¶ The command or option attempted is not supported by the server.服务器不支持尝试的命令或选项。New in version 3.5.版本3.5中新增。
-
exception
smtplib.
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 orlevel值为1或True
for level results in debug messages for connection and for all messages sent to and received from the server.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.向服务器发送命令cmd。The 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 argumentsself
,host
,port
.self
、host
、port
引发审核事件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检查ESMTP选项的响应,并存储它们以供has_extn()
.has_extn()
使用。Also sets several informational attributes: the message returned by the server is stored as the还设置几个信息属性:服务器返回的消息存储为ehlo_resp
attribute,does_esmtp
is set toTrue
orFalse
depending on whether the server supports ESMTP, andesmtp_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
设置为True
或False
,具体取决于服务器是否支持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或helo命令,此方法将调用ehlo()
and/orhelo()
if there has been no previousEHLO
orHELO
command this session.ehlo()
和/或helo()
。It tries ESMTP它首先尝试ESMTPEHLO
first.EHLO
。SMTPHeloError
The server didn’t reply properly to the服务器没有正确回复HELO
greeting.HELO
问候语。
-
SMTP.
has_extn
(name)¶ Return如果name位于服务器返回的SMTP服务扩展集中,则返回True
if name is in the set of SMTP service extensions returned by the server,False
otherwise.True
,否则返回False
。Case is ignored.忽略大小写。
-
SMTP.
verify
(address)¶ Check the validity of an address on this server using SMTP使用SMTPVRFY
.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许多网站禁用SMTPVRFY
in order to foil spammers.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
orHELO
command this session, this method tries ESMTPEHLO
first.EHLO
或HELO
命令,此方法将首先尝试ESMTPEHLO
。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.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 toinitial_response_ok传递给auth()
.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可选关键字参数initial_response_ok指定,对于支持它的身份验证方法,RFC 4954中指定的“初始响应”是否可以与AUTH
command, rather than requiring a challenge/response.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为指定的身份验证mechanism发出SMTP
AUTH
command for the specified authentication mechanism, and handle the challenge response via authobject.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 theauth
element ofesmtp_features
.AUTH
命令的参数;有效值列在esmtp_features
的auth
元素中。authobject
must be a callable object taking an optional single argument:必须是采用可选单个参数的可调用对象:data = authobject(challenge=None)
If optional keyword argument initial_response_ok is true,如果可选关键字参数initial_response_ok为authobject()
will be called first with no argument.true
,将首先调用authobject()
,而不使用参数。It can return the RFC 4954 “initial response” ASCII它可以返回RFC 4954“initial response”ASCII str,该字符串将使用AUTH命令进行编码并发送,如下所示。str
which will be encoded and sent with theAUTH
command as below.If the如果authobject()
does not support an initial response (e.g. because it requires a challenge), it should returnNone
when called withchallenge=None
.authobject()
不支持初始响应(例如,因为它需要质询),那么当使用challenge=None
调用时,它应该返回None
。If initial_response_ok is false, then如果initial_response_ok为authobject()
will not be called first withNone
.false
,则不会首先使用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 abytes
.None
,或者initial_response_ok为false
,将调用authobject()
来处理服务器的质询响应;它传递的质询参数将是一个字节。It should return ASCII它应该返回将以base64编码并发送到服务器的ASCIIstr
data that will be base64 encoded and sent to the server.str
data。TheSMTP
class providesauthobjects
for theCRAM-MD5
,PLAIN
, andLOGIN
mechanisms; they are namedSMTP.auth_cram_md5
,SMTP.auth_plain
, andSMTP.auth_login
respectively.SMTP
类为CRAM-MD5
、PLAIN
和LOGIN
机制提供authobjects
;它们分别命名为SMTP.auth_cram_md5
、SMTP.auth_plain
和SMTP.auth _login
。They all require that the它们都要求将user
andpassword
properties of theSMTP
instance are set to appropriate values.SMTP
实例的user
和password
属性设置为适当的值。User code does not normally need to call用户代码通常不需要直接调用auth
directly, but can instead call thelogin()
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如果提供了keyfile和certfile,则它们用于创建ssl.SSLContext
.ssl.SSLContext
。Optional context parameter is an可选context参数是ssl.SSLContext
object; This is an alternative to using a keyfile and a certfile and if specified both keyfile and certfile should beNone
.ssl.SSLContext
对象;这是使用keyfile和certfile的一种替代方法,如果指定了keyfile与certfiles,则两者都应为None
。If there has been no previous如果此会话中以前没有EHLO
orHELO
command this session, this method tries ESMTPEHLO
first.EHLO
或HELO
命令,此方法将首先尝试ESMTPEHLO
。Deprecated since version 3.6:自版本3.6起已弃用:keyfile and certfile are deprecated in favor of context.keyfile和certfile已被弃用,取而代之的是context。Please use请改用ssl.SSLContext.load_cert_chain()
instead, or letssl.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 (seeHAS_SNI
).SSLContext.check_hostname
和服务器名称指示符进行主机名检查(请参阅HAS_SNI
)。Changed in version 3.5:版本3.5中更改:The error raised for lack of STARTTLS support is now the由于缺少STARTTLS支持而引发的错误现在是SMTPNotSupportedError
subclass instead of the baseSMTPException
.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 inMAIL FROM
commands as mail_options.MAIL FROM
命令中使用的ESMTP选项列表(如8bitmime
)作为mail_options传递。ESMTP options (such as应与所有DSN
commands) that should be used with allRCPT
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(如果需要对不同的收件人使用不同的ESMTP选项,则必须使用低级方法,如mail()
,rcpt()
anddata()
to send the message.)mail()
、rcpt()
和data()
来发送消息。)Note
The from_addr and to_addrs parameters are used to construct the message envelope used by the transport agents.from_addr和to_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字符串使用ascii编解码器编码为字节,孤立字符\r
and\n
characters are converted to\r\n
characters.\r
和\n
字符转换为字符\r\n
。A byte string is not modified.字节字符串未修改。If there has been no previous如果此会话中以前没有EHLO
orHELO
command this session, this method tries ESMTPEHLO
first.EHLO
或HELO
命令,此方法将首先尝试ESMTPEHLO
。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).如果服务器执行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如果mail_options中包含SMTPUTF8
is included in mail_options, and the server supports it, from_addr and to_addrs may contain non-ASCII characters.SMTPUTF8
,并且服务器支持它,那么from_addr和to_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
mail_options中提供了SMTPUTF8
was given in the mail_options but is not supported by the server.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, andSMTPNotSupportedError
may be raised ifSMTPUTF8
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 anemail.message.Message
object.email.message.Message
对象表示的消息调用sendmail()
的方便方法。The arguments have the same meaning as for这些参数与sendmail()
, except that msg is aMessage
object.sendmail()
的含义相同,只是msg是一个Message
对象。If from_addr is如果from_addr为None
or to_addrs isNone
,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.None
或to_addrs为None
,则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如果消息包含多组Resent-*头,则会引发ValueError
is raised, since there is no way to unambiguously detect the most recent set of Resent- headers.ValueError
,因为无法明确检测最新的Resent-标头集。send_message
serializes msg usingBytesGenerator
with\r\n
as the linesep, and callssendmail()
to transmit the resulting message.send_message
使用BytesGenerator
配合\r\n
将msg序列化为linesep,并调用sendmail()
来传输生成的消息。Regardless of the values of from_addr and to_addrs,无论from_addr和to_addrs的值是多少,send_message
does not transmit any Bcc or Resent-Bcc headers that may appear in msg.send_message
都不会传输消息中可能出现的任何密件抄送或重新发送密件抄收头。If any of the addresses in from_addr and to_addrs contain non-ASCII characters and the server does not advertise如果from_addr和to_addr中的任何地址包含非ASCII字符,并且服务器不公布SMTPUTF8
support, anSMTPNotSupported
error is raised.SMTPUTF8
支持,则会引发SMTPNotSupported
错误。Otherwise the否则,将使用其Message
is serialized with a clone of itspolicy
with theutf8
attribute set toTrue
, andSMTPUTF8
andBODY=8BITMIME
are added to mail_options.policy
的克隆(utf8
属性设置为True
)对Message
进行序列化,并将SMTPUTF8
和BODY=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返回SMTPQUIT
command.QUIT
命令的结果。
Low-level methods corresponding to the standard SMTP/ESMTP commands 还支持对应于标准SMTP/ESMTP命令HELP
, RSET
, NOOP
, MAIL
, RCPT
, and DATA
are also supported. HELP
、RSET
、NOOP
、MAIL
、RCPT
和DATA
的低级方法。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()
发送该消息;请参阅电子邮件:示例。