smtplib --- SMTP 協定用戶端¶
原始碼: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. For
details of SMTP and ESMTP operation, consult RFC 821 (Simple Mail Transfer
Protocol) and RFC 1869 (SMTP Service Extensions).
可用性: not WASI.
此模組在 WebAssembly 平台上不起作用或無法使用。更多資訊請參閱 WebAssembly 平台。
- class smtplib.SMTP(host='', port=0, local_hostname=None, [timeout, ]source_address=None)¶
An
SMTPinstance encapsulates an SMTP connection. It has methods that support a full repertoire of SMTP and ESMTP operations. If the optional host and port parameters are given, the SMTPconnect()method is called with those parameters during initialization. If specified, local_hostname is used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the local hostname is found usingsocket.getfqdn(). If theconnect()call returns anything other than a success code, anSMTPConnectErroris raised. 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). If the timeout expires,TimeoutErroris raised. 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. It takes a 2-tuple(host, port), for the socket to bind to as its source address before connecting. If omitted (or if host or port are''and/or0respectively) the OS default behavior will be used.For normal use, you should only require the initialization/connect,
sendmail(), andSMTP.quit()methods. An example is included below.The
SMTPclass supports thewithstatement. When used like this, the SMTPQUITcommand is issued automatically when thewithstatement exits. E.g.:>>> from smtplib import SMTP >>> with SMTP("domain.org") as smtp: ... smtp.noop() ... (250, b'Ok') >>>
所有指令都會引發一個附帶引數
self、data的稽核事件smtplib.SMTP.send,其中data為即將傳送至遠端的位元組。在 3.3 版的變更: 新增對
with陳述式的支援。在 3.3 版的變更: 新增 source_address 引數。
在 3.5 版被加入: The SMTPUTF8 extension (RFC 6531) is now supported.
在 3.9 版的變更: If the timeout parameter is set to be zero, it will raise a
ValueErrorto prevent the creation of a non-blocking socket.
- class smtplib.SMTP_SSL(host='', port=0, local_hostname=None, *, [timeout, ]context=None, source_address=None)¶
An
SMTP_SSLinstance behaves exactly the same as instances ofSMTP.SMTP_SSLshould be used for situations where SSL is required from the beginning of the connection and usingstarttls()is not appropriate. If host is not specified, the local host is used. If port is zero, the standard SMTP-over-SSL port (465) is used. The optional arguments local_hostname, timeout and source_address have the same meaning as they do in theSMTPclass. context, also optional, can contain aSSLContextand allows configuring various aspects of the secure connection. Please read Security considerations for best practices.在 3.3 版的變更: 新增 context。
在 3.3 版的變更: 新增 source_address 引數。
在 3.4 版的變更: The class now supports hostname check with
ssl.SSLContext.check_hostnameand Server Name Indication (seessl.HAS_SNI).在 3.9 版的變更: If the timeout parameter is set to be zero, it will raise a
ValueErrorto prevent the creation of a non-blocking socket在 3.12 版的變更: The deprecated keyfile and certfile parameters have been removed.
- 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. It's common to use Unix sockets for LMTP, so our
connect()method must support that as well as a regular host:port server. The optional arguments local_hostname and source_address have the same meaning as they do in theSMTPclass. To specify a Unix socket, you must use an absolute path for host, starting with a '/'.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.
在 3.9 版的變更: 新增 timeout 選用參數。
A nice selection of exceptions is defined as well:
- exception smtplib.SMTPException¶
Subclass of
OSErrorthat 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
SMTPinstance 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.
- smtp_code¶
The error code.
- smtp_error¶
The error message.
- exception smtplib.SMTPSenderRefused¶
Sender address refused. In addition to the attributes set by on all
SMTPResponseExceptionexceptions, this sets 'sender' to the string that the SMTP server refused.
- exception smtplib.SMTPRecipientsRefused¶
All recipient addresses refused.
- recipients¶
A dictionary of exactly the same sort as returned by
SMTP.sendmail()containing the errors for each recipient.
- 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
HELOmessage.
- 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 - 簡易郵件傳輸協定
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.
SMTP 物件¶
SMTP 實例擁有以下方法:
- SMTP.set_debuglevel(level)¶
Set the debug output level. A value of 1 or
Truefor 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 版的變更: 新增 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,
SMTPServerDisconnectedwill be raised.
- 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). 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.引發一個附帶引數
self、host、port的稽核事件smtplib.connect。
- 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 thehelo_respattribute 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='')¶
Identify yourself to an ESMTP server using
EHLO. The hostname argument defaults to the fully qualified domain name of the local host. Examine the response for ESMTP option and store them for use byhas_extn(). Also sets several informational attributes: the message returned by the server is stored as theehlo_respattribute,does_esmtpis set toTrueorFalsedepending on whether the server supports ESMTP, andesmtp_featureswill be a dictionary containing the names of the SMTP service extensions this server supports, and their parameters (if any).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 bysendmail()when necessary.
- SMTP.ehlo_or_helo_if_needed()¶
This method calls
ehlo()and/orhelo()if there has been no previousEHLOorHELOcommand this session. It tries ESMTPEHLOfirst.SMTPHeloErrorThe server didn't reply properly to the
HELOgreeting.
- SMTP.has_extn(name)¶
Return
Trueif name is in the set of SMTP service extensions returned by the server,Falseotherwise. 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