Navigation

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).

An SMTP instance 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 SMTP connect() 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 using
socket.getfqdn(). If the connect() call returns anything other
than a success code, an SMTPConnectError is 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, socket.timeout is
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/or 0 respectively)
the OS default behavior will be used.

For normal use, you should only require the initialization/connect,
sendmail(), and SMTP.quit() methods.
An example is included below.

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.:

An SMTP_SSL instance behaves exactly the same as instances of
SMTP. SMTP_SSL should be used for situations where SSL is
required from the beginning of the connection and using starttls() 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 the SMTP class. context, also optional,
can contain a SSLContext and allows configuring various
aspects of the secure connection. 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.

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 the SMTP class. 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.

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.

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.

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.

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.

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.

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 by 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).

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.

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.

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:

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.

Changed in version 3.5: SMTPNotSupportedError may be raised, and the
initial_response_ok parameter was added.

Issue an SMTPAUTH 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 strdata 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.

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. The caller may pass a list of ESMTP options
(such as 8bitmime) to be used in MAILFROM commands as mail_options.
ESMTP options (such as DSN commands) that should be used with all RCPT
commands can be passed as 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.)

Note

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.

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).

This is a convenience method for calling sendmail() with the message
represented by an email.message.Message object. The arguments have
the same meaning as for sendmail(), except that msg is a Message
object.

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.
to_addrs combines the values (if any) of the To,
Cc, and Bcc fields from msg. If exactly one
set of Resent-* headers appear in the message, the regular
headers are ignored and the Resent-* headers are used instead.
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.

send_message serializes msg using
BytesGenerator with \r\n as the linesep, and
calls sendmail() to transmit the resulting message. 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. 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. 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.

New in version 3.2.

New in version 3.5: Support for internationalized addresses (SMTPUTF8).

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.

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.