API Reference

The send Coroutine

async aiosmtplib.send(message, sender=None, recipients=None, mail_options=None, rcpt_options=None, hostname='localhost', port=None, username=None, password=None, local_hostname=None, source_address=None, timeout=60, use_tls=False, start_tls=None, validate_certs=True, client_cert=None, client_key=None, tls_context=None, cert_bundle=None, socket_path=None, sock=None)[source]

Send an email message. On await, connects to the SMTP server using the details provided, sends the message, then disconnects.

Parameters:
  • message (Union[EmailMessage, Message, str, bytes]) – Message text. Either an email.message.EmailMessage object, str or bytes. If an email.message.EmailMessage object is provided, sender and recipients set in the message headers will be used, unless overridden by the respective keyword arguments.

  • sender – From email address. Not required if an email.message.EmailMessage object is provided for the message argument.

  • recipients – Recipient email addresses. Not required if an email.message.EmailMessage object is provided for the message argument.

  • hostname – Server name (or IP) to connect to. Defaults to “localhost”.

  • port – Server port. Defaults 465 if use_tls is True, 587 if start_tls is True, or 25 otherwise.

  • username – Username to login as after connect.

  • password – Password for login after connect.

  • local_hostname – The hostname of the client. If specified, used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the result of socket.getfqdn(). Note that getfqdn will block the event loop.

  • source_address – Takes a 2-tuple (host, port) for the socket to bind to as its source address before connecting. If the host is ‘’ and port is 0, the OS default behavior will be used.

  • timeout – Default timeout value for the connection, in seconds. Defaults to 60.

  • use_tls – If True, make the initial connection to the server over TLS/SSL. Mutually exclusive with start_tls; if the server uses STARTTLS, use_tls should be False.

  • start_tls – Flag to initiate a STARTTLS upgrade on connect. If None (the default), upgrade will be initiated if supported by the server. If True, and upgrade will be initiated regardless of server support. If False, no upgrade will occur. Mutually exclusive with use_tls.

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

  • socket_path – Path to a Unix domain socket. Not compatible with hostname or port. Accepts str, bytes, or a pathlike object.

  • sock – An existing, connected socket object. If given, none of hostname, port, or socket_path should be provided.

Raises:

ValueError – required arguments missing or mutually exclusive options provided

Return type:

Tuple[Dict[str, SMTPResponse], str]

The SMTP Class

class aiosmtplib.SMTP(hostname='localhost', port=None, username=None, password=None, local_hostname=None, source_address=None, timeout=60, use_tls=False, start_tls=None, validate_certs=True, client_cert=None, client_key=None, tls_context=None, cert_bundle=None, socket_path=None, sock=None)[source]

Main SMTP client class.

Basic usage:

>>> event_loop = asyncio.get_event_loop()
>>> smtp = aiosmtplib.SMTP(hostname="127.0.0.1", port=1025)
>>> event_loop.run_until_complete(smtp.connect())
(220, ...)
>>> sender = "root@localhost"
>>> recipients = ["somebody@localhost"]
>>> message = "Hello World"
>>> send = smtp.sendmail(sender, recipients, "Hello World")
>>> event_loop.run_until_complete(send)
({}, 'OK')

Keyword arguments can be provided either on __init__() or when calling the connect() method. Note that in both cases these options are saved for later use; subsequent calls to connect() will use the same options, unless new ones are provided.

__init__(hostname='localhost', port=None, username=None, password=None, local_hostname=None, source_address=None, timeout=60, use_tls=False, start_tls=None, validate_certs=True, client_cert=None, client_key=None, tls_context=None, cert_bundle=None, socket_path=None, sock=None)[source]
Parameters:
  • hostname – Server name (or IP) to connect to. Defaults to “localhost”.

  • port – Server port. Defaults 465 if use_tls is True, 587 if start_tls is True, or 25 otherwise.

  • username – Username to login as after connect.

  • password – Password for login after connect.

  • local_hostname – The hostname of the client. If specified, used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the result of socket.getfqdn(). Note that getfqdn will block the event loop.

  • source_address – Takes a 2-tuple (host, port) for the socket to bind to as its source address before connecting. If the host is ‘’ and port is 0, the OS default behavior will be used.

  • timeout – Default timeout value for the connection, in seconds. Defaults to 60.

  • use_tls – If True, make the initial connection to the server over TLS/SSL. Mutually exclusive with start_tls; if the server uses STARTTLS, use_tls should be False.

  • start_tls – Flag to initiate a STARTTLS upgrade on connect. If None (the default), upgrade will be initiated if supported by the server. If True, and upgrade will be initiated regardless of server support. If False, no upgrade will occur. Mutually exclusive with use_tls.

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

  • socket_path – Path to a Unix domain socket. Not compatible with hostname or port. Accepts str, bytes, or a pathlike object.

  • sock – An existing, connected socket object. If given, none of hostname, port, or socket_path should be provided.

Raises:

ValueError – mutually exclusive options provided

async auth_crammd5(username, password, timeout=Default.token)[source]

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

async auth_login(username, password, timeout=Default.token)[source]

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

async auth_plain(username, password, timeout=Default.token)[source]

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()[source]

Closes the connection.

Return type:

None

async connect(hostname=Default.token, port=Default.token, username=Default.token, password=Default.token, local_hostname=Default.token, source_address=Default.token, timeout=Default.token, use_tls=None, start_tls=Default.token, validate_certs=None, client_cert=Default.token, client_key=Default.token, tls_context=Default.token, cert_bundle=Default.token, socket_path=Default.token, sock=Default.token)[source]

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. Defaults to “localhost”.

  • port – Server port. Defaults 465 if use_tls is True, 587 if start_tls is True, or 25 otherwise.

  • username – Username to login as after connect.

  • password – Password for login after connect.

  • local_hostname – The hostname of the client. If specified, used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the result of socket.getfqdn(). Note that getfqdn will block the event loop.

  • source_address – Takes a 2-tuple (host, port) for the socket to bind to as its source address before connecting. If the host is ‘’ and port is 0, the OS default behavior will be used.

  • timeout – Default timeout value for the connection, in seconds. Defaults to 60.

  • use_tls – If True, make the initial connection to the server over TLS/SSL. Mutually exclusive with start_tls; if the server uses STARTTLS, use_tls should be False.

  • start_tls – Flag to initiate a STARTTLS upgrade on connect. If None (the default), upgrade will be initiated if supported by the server. If True, and upgrade will be initiated regardless of server support. If False, no upgrade will occur. Mutually exclusive with use_tls.

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

  • socket_path – Path to a Unix domain socket. Not compatible with hostname or port. Accepts str, bytes, or a pathlike object.

  • sock – An existing, connected socket object. If given, none of hostname, port, or socket_path should be provided.

Raises:

ValueError – mutually exclusive options provided

Return type:

SMTPResponse

async data(message, timeout=Default.token)[source]

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

Raises:
Return type:

SMTPResponse

async ehlo(hostname=None, timeout=Default.token)[source]

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

async execute_command(*args, timeout=Default.token)[source]

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

async expn(address, options=None, timeout=Default.token)[source]

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)[source]

Get extra info from the transport. Supported keys:

  • peername

  • socket

  • sockname

  • compression

  • cipher

  • peercert

  • sslcontext

  • sslobject

Raises:

SMTPServerDisconnected – connection lost

Return type:

Any

async helo(hostname=None, timeout=Default.token)[source]

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

async help(timeout=Default.token)[source]

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

Raises:

SMTPResponseException – on unexpected server response code

Return type:

str

property is_connected: bool

Check if our transport is still connected.

Return type:

bool

property is_ehlo_or_helo_needed: bool

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

Return type:

bool

property local_hostname: str

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

Return type:

str

async login(username, password, timeout=Default.token)[source]

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

async mail(sender, options=None, encoding='ascii', timeout=Default.token)[source]

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

async noop(timeout=Default.token)[source]

Send an SMTP NOOP command, which does nothing.

Raises:

SMTPResponseException – on unexpected server response code

Return type:

SMTPResponse

async quit(timeout=Default.token)[source]

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

async rcpt(recipient, options=None, encoding='ascii', timeout=Default.token)[source]

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

async rset(timeout=Default.token)[source]

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

async send_message(message, sender=None, recipients=None, mail_options=None, rcpt_options=None, timeout=Default.token)[source]

Sends an email.message.EmailMessage object.

Arguments are as for sendmail(), except that message is an email.message.EmailMessage object. If sender is None or recipients is None, these arguments are taken from the headers of the EmailMessage 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 EmailMessage object will not be transmitted. The EmailMessage 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:
  • ValueError – on more than one Resent header block on no sender kwarg or From header in message on no recipients kwarg or To, Cc or Bcc header in message

  • SMTPRecipientsRefused – delivery to all recipients failed

  • SMTPResponseException – on invalid response

Return type:

Tuple[Dict[str, SMTPResponse], str]

send_message_sync(*args, **kwargs)[source]

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

Return type:

Tuple[Dict[str, SMTPResponse], str]

async sendmail(sender, recipients, message, mail_options=None, rcpt_options=None, timeout=Default.token)[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:

>>> event_loop = asyncio.get_event_loop()
>>> smtp = aiosmtplib.SMTP(hostname="127.0.0.1", port=1025)
>>> event_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)
>>> event_loop.run_until_complete(send_coro)
({}, 'OK')
>>> event_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(*args, **kwargs)[source]

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

Return type:

Tuple[Dict[str, SMTPResponse], str]

async starttls(server_hostname=None, validate_certs=None, client_cert=Default.token, client_key=Default.token, cert_bundle=Default.token, tls_context=Default.token, timeout=Default.token)[source]

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

property supported_auth_methods: List[str]

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

Return type:

List[str]

supports_extension(extension)[source]

Tests if the server supports the ESMTP service extension given.

Return type:

bool

async vrfy(address, options=None, timeout=Default.token)[source]

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(code: int, message: str)[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
code: int

Alias for field number 0

message: str

Alias for field number 1

Status Codes

class aiosmtplib.typing.SMTPStatus(value)[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
tls_not_available = 454
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: SMTPResponseException

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

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

Bases: SMTPException, ConnectionError

An error occurred while connecting to the SMTP server.

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

Bases: SMTPTimeoutError, SMTPConnectError

A timeout occurred while connecting to the SMTP server.

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

Bases: 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: SMTPResponseException

Server refused HELO or EHLO.

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

Bases: SMTPException

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

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

Bases: SMTPTimeoutError

A timeout occurred while waiting for a response from the SMTP server.

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

Bases: SMTPResponseException

SMTP server refused a message recipient.

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

Bases: SMTPException

SMTP server refused multiple recipients.

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

Bases: SMTPException

Base class for all server responses with error codes.

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

Bases: SMTPResponseException

SMTP server refused the message sender.

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

Bases: SMTPException, ConnectionError

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

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

Bases: SMTPException, TimeoutError

A timeout occurred while performing a network operation.