API Reference

The SMTP Class

class aiosmtplib.SMTP(*args, **kwargs)[source]

Main SMTP client class.

Basic usage:

>>> loop = asyncio.get_event_loop()
>>> smtp = aiosmtplib.SMTP(hostname="127.0.0.1", port=1025, loop=loop)
>>> loop.run_until_complete(smtp.connect())
(220, ...)
>>> sender = "root@localhost"
>>> recipients = ["somebody@localhost"]
>>> message = "Hello World"
>>> send = smtp.sendmail(sender, recipients, "Hello World")
>>> loop.run_until_complete(send)
({}, 'OK')
__init__(*args, **kwargs)[source]
Parameters:
  • hostname – Server name (or IP) to connect to
  • port – Server port. Defaults to 25 if use_tls is False, 465 if use_tls is True.
  • source_address – The hostname of the client. Defaults to the result of socket.getfqdn(). Note that this call blocks.
  • timeout – Default timeout value for the connection, in seconds. Defaults to 60.
  • loop – event loop to run on. If not set, uses asyncio.get_event_loop().
  • use_tls – If True, make the initial connection to the server over TLS/SSL. Note that if the server supports STARTTLS only, this should be False.
  • validate_certs – Determines if server certificates are validated. Defaults to True.
  • client_cert – Path to client side certificate, for TLS verification.
  • client_key – Path to client side key, for TLS verification.
  • tls_context – An existing ssl.SSLContext, for TLS verification. Mutually exclusive with client_cert/ client_key.
  • cert_bundle – Path to certificate bundle, for TLS verification.
Raises:

ValueError – mutually exclusive options provided

Return type:

None

auth_crammd5(username, password, timeout=<Default.token: 0>)

CRAM-MD5 auth uses the password as a shared secret to MD5 the server’s response.

Example:

250 AUTH CRAM-MD5
auth cram-md5
334 PDI0NjA5LjEwNDc5MTQwNDZAcG9wbWFpbC5TcGFjZS5OZXQ+
dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw
Return type:SMTPResponse
auth_login(username, password, timeout=<Default.token: 0>)

LOGIN auth sends the Base64 encoded username and password in sequence.

Example:

250 AUTH LOGIN PLAIN CRAM-MD5
auth login avlsdkfj
334 UGFzc3dvcmQ6
avlsdkfj

Note that there is an alternate version sends the username as a separate command:

250 AUTH LOGIN PLAIN CRAM-MD5
auth login
334 VXNlcm5hbWU6
avlsdkfj
334 UGFzc3dvcmQ6
avlsdkfj

However, since most servers seem to support both, we send the username with the initial request.

Return type:SMTPResponse
auth_plain(username, password, timeout=<Default.token: 0>)

PLAIN auth encodes the username and password in one Base64 encoded string. No verification message is required.

Example:

220-esmtp.example.com
AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz
235 ok, go ahead (#2.0.0)
Return type:SMTPResponse
close()

Makes sure we reset ESMTP state on close.

Return type:None
connect(hostname=None, port=None, source_address=<Default.token: 0>, timeout=<Default.token: 0>, loop=None, use_tls=None, validate_certs=None, client_cert=<Default.token: 0>, client_key=<Default.token: 0>, tls_context=<Default.token: 0>, cert_bundle=<Default.token: 0>)

Initialize a connection to the server. Options provided to connect() take precedence over those used to initialize the class.

Parameters:
  • hostname – Server name (or IP) to connect to
  • port – Server port. Defaults to 25 if use_tls is False, 465 if use_tls is True.
  • source_address – The hostname of the client. Defaults to the result of socket.getfqdn(). Note that this call blocks.
  • timeout – Default timeout value for the connection, in seconds. Defaults to 60.
  • loop – event loop to run on. If not set, uses asyncio.get_event_loop().
  • use_tls – If True, make the initial connection to the server over TLS/SSL. Note that if the server supports STARTTLS only, this should be False.
  • validate_certs – Determines if server certificates are validated. Defaults to True.
  • client_cert – Path to client side certificate, for TLS.
  • client_key – Path to client side key, for TLS.
  • tls_context – An existing ssl.SSLContext, for TLS. Mutually exclusive with client_cert/client_key.
  • cert_bundle – Path to certificate bundle, for TLS verification.
Raises:

ValueError – mutually exclusive options provided

Return type:

SMTPResponse

data(message, timeout=<Default.token: 0>)

Send an SMTP DATA command, followed by the message given. This method transfers the actual email content to the server.

Raises:
Return type:

SMTPResponse

ehlo(hostname=None, timeout=<Default.token: 0>)

Send the SMTP EHLO command. Hostname to send for this command defaults to the FQDN of the local host.

Raises:SMTPHeloError – on unexpected server response code
Return type:SMTPResponse
execute_command(*args, timeout=<Default.token: 0>)

Check that we’re connected, if we got a timeout value, and then pass the command to the protocol.

Raises:SMTPServerDisconnected – connection lost
Return type:SMTPResponse
expn(address, timeout=<Default.token: 0>)

Send an SMTP EXPN command, which expands a mailing list. Not many servers support this command.

Raises:SMTPResponseException – on unexpected server response code
Return type:SMTPResponse
get_transport_info(key)

Get extra info from the transport. Supported keys:

  • peername
  • socket
  • sockname
  • compression
  • cipher
  • peercert
  • sslcontext
  • sslobject
Raises:SMTPServerDisconnected – connection lost
Return type:Any
helo(hostname=None, timeout=<Default.token: 0>)

Send the SMTP HELO command. Hostname to send for this command defaults to the FQDN of the local host.

Raises:SMTPHeloError – on unexpected server response code
Return type:SMTPResponse
help(timeout=<Default.token: 0>)

Send the SMTP HELP command, which responds with help text.

Raises:SMTPResponseException – on unexpected server response code
Return type:str
is_connected

Check if our transport is still connected.

Return type:bool
is_ehlo_or_helo_needed

Check if we’ve already received a response to an EHLO or HELO command.

Return type:bool
login(username, password, timeout=<Default.token: 0>)

Tries to login with supported auth methods.

Some servers advertise authentication methods they don’t really support, so if authentication fails, we continue until we’ve tried all methods.

Return type:SMTPResponse
mail(sender, options=None, timeout=<Default.token: 0>)

Send an SMTP MAIL command, which specifies the message sender and begins a new mail transfer session (“envelope”).

Raises:SMTPSenderRefused – on unexpected server response code
Return type:SMTPResponse
noop(timeout=<Default.token: 0>)

Send an SMTP NOOP command, which does nothing.

Raises:SMTPResponseException – on unexpected server response code
Return type:SMTPResponse
quit(timeout=<Default.token: 0>)

Send the SMTP QUIT command, which closes the connection. Also closes the connection from our side after a response is received.

Raises:SMTPResponseException – on unexpected server response code
Return type:SMTPResponse
rcpt(recipient, options=None, timeout=<Default.token: 0>)

Send an SMTP RCPT command, which specifies a single recipient for the message. This command is sent once per recipient and must be preceded by ‘MAIL’.

Raises:SMTPRecipientRefused – on unexpected server response code
Return type:SMTPResponse
rset(timeout=<Default.token: 0>)

Send an SMTP RSET command, which resets the server’s envelope (the envelope contains the sender, recipient, and mail data).

Raises:SMTPResponseException – on unexpected server response code
Return type:SMTPResponse
send_message(message, sender=None, recipients=None, mail_options=None, rcpt_options=None, timeout=<Default.token: 0>)[source]

Sends an email.message.Message object.

Arguments are as for sendmail(), except that message is an email.message.Message object. If sender is None or recipients is None, these arguments are taken from the headers of the Message as described in RFC 2822. Regardless of the values of sender and recipients, any Bcc field (or Resent-Bcc field, when the Message is a resent) of the Message object will not be transmitted. The Message object is then serialized using email.generator.Generator and sendmail() is called to transmit the message.

‘Resent-Date’ is a mandatory field if the Message is resent (RFC 2822 Section 3.6.6). In such a case, we use the ‘Resent-*’ fields. However, if there is more than one ‘Resent-‘ block there’s no way to unambiguously determine which one is the most recent in all cases, so rather than guess we raise a ValueError in that case.

Raises:
Return type:

Tuple[Dict[str, SMTPResponse], str]

send_message_sync(message, sender=None, recipients=None, mail_options=None, rcpt_options=None, timeout=<Default.token: 0>)[source]

Synchronous version of send_message(). This method starts the event loop to connect, send the message, and disconnect.

Return type:Tuple[Dict[str, SMTPResponse], str]
sendmail(sender, recipients, message, mail_options=None, rcpt_options=None, timeout=<Default.token: 0>)[source]

This command performs an entire mail transaction.

The arguments are:
  • sender: The address sending this mail.
  • recipients: A list of addresses to send this mail to. A bare
    string will be treated as a list with 1 address.
  • message: The message string to send.
  • mail_options: List of options (such as ESMTP 8bitmime) for the
    MAIL command.
  • rcpt_options: List of options (such as DSN commands) for all the
    RCPT commands.

message must be a string containing characters in the ASCII range. The string is encoded to bytes using the ascii codec, and lone \r and \n characters are converted to \r\n characters.

If there has been no previous HELO or EHLO command this session, this method tries EHLO first.

This method will return normally if the mail is accepted for at least one recipient. It returns a tuple consisting of:

  • an error 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.
  • the message sent by the server in response to the DATA command
    (often containing a message id)

Example:

>>> loop = asyncio.get_event_loop()
>>> smtp = aiosmtplib.SMTP(hostname="127.0.0.1", port=1025)
>>> loop.run_until_complete(smtp.connect())
(220, ...)
>>> recipients = ["one@one.org", "two@two.org", "3@three.org"]
>>> message = "From: Me@my.org\nSubject: testing\nHello World"
>>> send_coro = smtp.sendmail("me@my.org", recipients, message)
>>> loop.run_until_complete(send_coro)
({}, 'OK')
>>> loop.run_until_complete(smtp.quit())
(221, Bye)

In the above example, the message was accepted for delivery for all three addresses. If delivery had been only successful to two of the three addresses, and one was rejected, the response would look something like:

(
    {"nobody@three.org": (550, "User unknown")},
    "Written safely to disk. #902487694.289148.12219.",
)

If delivery is not successful to any addresses, SMTPRecipientsRefused is raised.

If SMTPResponseException is raised by this method, we try to send an RSET command to reset the server envelope automatically for the next attempt.

Raises:
Return type:

Tuple[Dict[str, SMTPResponse], str]

sendmail_sync(sender, recipients, message, mail_options=None, rcpt_options=None, timeout=<Default.token: 0>)[source]

Synchronous version of sendmail(). This method starts the event loop to connect, send the message, and disconnect.

Return type:Tuple[Dict[str, SMTPResponse], str]
source_address

Get the system hostname to be sent to the SMTP server. Simply caches the result of socket.getfqdn().

Return type:str
starttls(server_hostname=None, validate_certs=None, client_cert=<Default.token: 0>, client_key=<Default.token: 0>, cert_bundle=<Default.token: 0>, tls_context=<Default.token: 0>, timeout=<Default.token: 0>)

Puts the connection to the SMTP server into TLS mode.

If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first.

If the server supports TLS, this will encrypt the rest of the SMTP session. If you provide the keyfile and certfile parameters, the identity of the SMTP server and client can be checked (if validate_certs is True). You can also provide a custom SSLContext object. If no certs or SSLContext is given, and TLS config was provided when initializing the class, STARTTLS will use to that, otherwise it will use the Python defaults.

Raises:
Return type:

SMTPResponse

supported_auth_methods

Get all AUTH methods supported by the both server and by us.

Return type:List[str]
supports_extension(extension)

Tests if the server supports the ESMTP service extension given.

Return type:bool
vrfy(address, timeout=<Default.token: 0>)

Send an SMTP VRFY command, which tests an address for validity. Not many servers support this command.

Raises:SMTPResponseException – on unexpected server response code
Return type:SMTPResponse

Server Responses

class aiosmtplib.response.SMTPResponse[source]

NamedTuple of server response code and server response message.

code and message can be accessed via attributes or indexes:

>>> response = SMTPResponse(200, "OK")
>>> response.message
'OK'
>>> response[0]
200
>>> response.code
200

Status Codes

class aiosmtplib.status.SMTPStatus[source]

Defines SMTP statuses for code readability.

See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html

access_denied = 530
auth_continue = 334
auth_failed = 535
auth_successful = 235
bad_command_sequence = 503
cannot_vrfy = 252
closing = 221
command_not_implemented = 502
completed = 250
domain_does_not_accept_mail = 521
domain_unavailable = 421
error_processing = 451
help_message = 214
insufficient_storage = 452
invalid_response = -1
mailbox_does_not_exist = 550
mailbox_name_invalid = 553
mailbox_unavailable = 450
parameter_not_implemented = 504
ready = 220
start_input = 354
storage_exceeded = 552
syntax_error = 555
system_status_ok = 211
transaction_failed = 554
unrecognized_command = 500
unrecognized_parameters = 501
user_not_local = 551
will_forward = 251

Exceptions

exception aiosmtplib.errors.SMTPAuthenticationError(code, message)[source]

Bases: aiosmtplib.errors.SMTPResponseException

Server refused our AUTH request; may be caused by invalid credentials.

exception aiosmtplib.errors.SMTPConnectError(message)[source]

Bases: aiosmtplib.errors.SMTPException, ConnectionError

An error occurred while connecting to the SMTP server.

exception aiosmtplib.errors.SMTPDataError(code, message)[source]

Bases: aiosmtplib.errors.SMTPResponseException

Server refused DATA content.

exception aiosmtplib.errors.SMTPException(message)[source]

Bases: Exception

Base class for all SMTP exceptions.

exception aiosmtplib.errors.SMTPHeloError(code, message)[source]

Bases: aiosmtplib.errors.SMTPResponseException

Server refused HELO or EHLO.

exception aiosmtplib.errors.SMTPNotSupported(code, message)[source]

Bases: aiosmtplib.errors.SMTPResponseException

A command or argument sent to the SMTP server is not supported.

exception aiosmtplib.errors.SMTPRecipientRefused(code, message, recipient)[source]

Bases: aiosmtplib.errors.SMTPResponseException

SMTP server refused a message recipient.

exception aiosmtplib.errors.SMTPRecipientsRefused(recipients)[source]

Bases: aiosmtplib.errors.SMTPException

SMTP server refused multiple recipients.

exception aiosmtplib.errors.SMTPResponseException(code, message)[source]

Bases: aiosmtplib.errors.SMTPException

Base class for all server responses with error codes.

exception aiosmtplib.errors.SMTPSenderRefused(code, message, sender)[source]

Bases: aiosmtplib.errors.SMTPResponseException

SMTP server refused the message sender.

exception aiosmtplib.errors.SMTPServerDisconnected(message)[source]

Bases: aiosmtplib.errors.SMTPException, ConnectionError

The connection was lost unexpectedly, or a command was run that requires a connection.

exception aiosmtplib.errors.SMTPTimeoutError(message)[source]

Bases: aiosmtplib.errors.SMTPException, concurrent.futures._base.TimeoutError

A timeout occurred while performing a network operation.