💎 PREMIUM: /library/smtplib.html - Complete Album!
smtplib — SMTP protocol client¶
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. For
details of SMTP and ESMTP operation, consult RFC 821 (Simple Mail Transfer
Protocol) and RFC 1869 (SMTP Service Extensions).
Availability: not WASI.
This module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.
- 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') >>>
All commands will raise an auditing event
smtplib.SMTP.sendwith argumentsselfanddata, wheredatais the bytes about to be sent to the remote host.Changed in version 3.3: Support for the
withstatement was added.Changed in version 3.3: source_address argument was added.
Added in version 3.5: The SMTPUTF8 extension (RFC 6531) is now supported.
Changed in version 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.Changed in version 3.3: context was added.
Changed in version 3.3: The source_address argument was added.
Changed in version 3.4: The class now supports hostname check with
ssl.SSLContext.check_hostnameand Server Name Indication (seessl.HAS_SNI).Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a
ValueErrorto prevent the creation of a non-blocking socketChanged in version 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.
Changed in version 3.9: The optional timeout parameter was added.
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.Changed in version 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.
Added in version 3.5.
- exception smtplib.SMTPAuthenticationError¶
SMTP authentication went wrong. Most probably the server didn’t accept the username/password combination provided.
See also
- 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.
SMTP Objects¶
An SMTP instance has the following methods:
- 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.Changed in version 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,
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.Raises an auditing event
smtplib.connectwith argumentsself,host,port.
- 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.