aiosmtplib¶
Quickstart¶
import asyncio
from email.message import EmailMessage
import aiosmtplib
message = EmailMessage()
message["From"] = "root@localhost"
message["To"] = "somebody@example.com"
message["Subject"] = "Hello World!"
message.set_content("Sent via aiosmtplib")
loop = asyncio.get_event_loop()
loop.run_until_complete(aiosmtplib.send(message, hostname="127.0.0.1", port=25))
Requirements¶
Python 3.5.2+, compiled with SSL support, is required.
Bug reporting¶
Bug reports (and feature requests) are welcome via Github issues.
User’s Guide¶
Sending Messages¶
Sending Message Objects¶
To send a message, create an email.message.EmailMessage
object, set
appropriate headers (“From” and one of “To”, “Cc” or “Bcc”, at minimum), then
pass it to send()
with the hostname and port of an SMTP server.
For details on creating email.message.EmailMessage
objects, see
the stdlib documentation examples.
Note
Confusingly, email.message.Message
objects are part of the
legacy email API (prior to Python 3.3), while email.message.EmailMessage
objects support email policies other than the older email.policy.Compat32
.
Use email.message.EmailMessage
where possible; it makes headers easier to
work with.
import asyncio
from email.message import EmailMessage
import aiosmtplib
async def send_hello_world():
message = EmailMessage()
message["From"] = "root@localhost"
message["To"] = "somebody@example.com"
message["Subject"] = "Hello World!"
message.set_content("Sent via aiosmtplib")
await aiosmtplib.send(message, hostname="127.0.0.1", port=1025)
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(send_hello_world())
Multipart Messages¶
Pass email.mime.multipart.MIMEMultipart
objects to send()
to
send messages with both HTML text and plain text alternatives.
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
message = MIMEMultipart("alternative")
message["From"] = "root@localhost"
message["To"] = "somebody@example.com"
message["Subject"] = "Hello World!"
plain_text_message = MIMEText("Sent via aiosmtplib", "plain", "utf-8")
html_message = MIMEText(
"<html><body><h1>Sent via aiosmtplib</h1></body></html>", "html", "utf-8"
)
message.attach(plain_text_message)
message.attach(html_message)
Sending Raw Messages¶
You can also send a str
or bytes
message, by providing the sender
and recipients
keyword arguments.
import asyncio
import aiosmtplib
async def send_hello_world():
message = """To: somebody@example.com
From: root@localhost
Subject: Hello World!
Sent via aiosmtplib
"""
await aiosmtplib.send(
message,
sender="root@localhost",
recipients=["somebody@example.com"],
hostname="127.0.0.1",
port=1025
)
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(send_hello_world())
Authentication¶
To authenticate, pass the username
and password
keyword arguments to
send()
.
await send(
message,
hostname="127.0.0.1",
port=1025,
username="test",
password="test"
)
Connection Options¶
Connecting Over TLS/SSL¶
If an SMTP server supports direct connection via TLS/SSL, pass
use_tls=True
.
await send(message, hostname="smtp.gmail.com", port=465, use_tls=True)
STARTTLS connections¶
Many SMTP servers support the STARTTLS extension over port 587. When using
STARTTLS, the initial connection is made over plaintext, and after connecting
a STARTTLS command is sent, which initiates the upgrade to a secure connection.
To connect to a server that uses STARTTLS, set start_tls
to True
.
await send(message, hostname="smtp.gmail.com", port=587, start_tls=True)
The SMTP Client Class¶
Use the SMTP
class as a client directly when you want more control
over the email sending process than the send()
async function provides.
Connecting to an SMTP Server¶
Initialize a new SMTP
instance, then await its SMTP.connect()
coroutine. Initializing an instance does not automatically connect to the
server, as that is a blocking operation.
import asyncio
from aiosmtplib import SMTP
client = SMTP()
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(client.connect(hostname="127.0.0.1", port=1025))
Connecting over TLS/SSL¶
If an SMTP server supports direct connection via TLS/SSL, pass use_tls=True
when initializing the SMTP instance (or when calling SMTP.connect()
).
smtp_client = aiosmtplib.SMTP(hostname="smtp.gmail.com", port=465, use_tls=True)
await smtp_client.connect()
STARTTLS connections¶
Many SMTP servers support the STARTTLS extension over port 587. When using
STARTTLS, the initial connection is made over plaintext, and after connecting
a STARTTLS command is sent which initiates the upgrade to a secure connection.
To connect to a server that uses STARTTLS, set use_tls
to False
when
connecting, and call SMTP.starttls()
on the client.
smtp_client = aiosmtplib.SMTP(hostname="smtp.gmail.com", port=587, use_tls=False)
await smtp_client.connect()
await smtp_client.starttls()
Connecting via async context manager¶
Instances of the SMTP
class can also be used as an async context
manager, which will automatically connect/disconnect on entry/exit.
import asyncio
from email.message import EmailMessage
from aiosmtplib import SMTP
async def say_hello():
message = EmailMessage()
message["From"] = "root@localhost"
message["To"] = "somebody@example.com"
message["Subject"] = "Hello World!"
message.set_content("Sent via aiosmtplib")
smtp_client = SMTP(hostname="127.0.0.1", port=1025)
async with smtp_client:
await smtp_client.send_message(message)
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(say_hello())
Sending Messages¶
SMTP.send_message()
¶
Use this method to send email.message.EmailMessage
objects, including
email.mime
subclasses such as email.mime.text.MIMEText
.
For details on creating email.message.Message
objects, see the
stdlib documentation examples.
import asyncio
from email.mime.text import MIMEText
from aiosmtplib import SMTP
mime_message = MIMEText("Sent via aiosmtplib")
mime_message["From"] = "root@localhost"
mime_message["To"] = "somebody@example.com"
mime_message["Subject"] = "Hello World!"
async def send_with_send_message(message):
smtp_client = SMTP(hostname="127.0.0.1", port=1025)
await smtp_client.connect()
await smtp_client.send_message(message)
await smtp_client.quit()
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(send_with_send_message(mime_message))
Pass email.mime.multipart.MIMEMultipart
objects to
SMTP.send_message()
to send messages with both HTML text and plain text
alternatives.
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
message = MIMEMultipart("alternative")
message["From"] = "root@localhost"
message["To"] = "somebody@example.com"
message["Subject"] = "Hello World!"
message.attach(MIMEText("hello", "plain", "utf-8"))
message.attach(MIMEText("<html><body><h1>Hello</h1></body></html>", "html", "utf-8"))
smtp_client = SMTP(hostname="127.0.0.1", port=1025)
event_loop.run_until_complete(smtp_client.connect())
event_loop.run_until_complete(smtp_client.send_message(message))
event_loop.run_until_complete(smtp_client.quit())
SMTP.sendmail()
¶
Use SMTP.sendmail()
to send raw messages. Note that when using this
method, you must format the message headers yourself.
import asyncio
from aiosmtplib import SMTP
sender = "root@localhost"
recipients = ["somebody@example.com"]
message = """To: somebody@example.com
From: root@localhost
Subject: Hello World!
Sent via aiosmtplib
"""
async def send_with_sendmail():
smtp_client = SMTP(hostname="127.0.0.1", port=1025)
await smtp_client.connect()
await smtp_client.sendmail(sender, recipients, message)
await smtp_client.quit()
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(send_with_sendmail())
Timeouts¶
All commands accept a timeout
keyword argument of a numerical value in
seconds. This value is used for all socket operations, and will raise
SMTPTimeoutError
if exceeded. Timeout values passed to send()
,
SMTP.__init__()
or SMTP.connect()
will be used as the default
value for commands executed on the connection.
The default timeout is 60 seconds.
Parallel Execution¶
SMTP is a sequential protocol. Multiple commands must be sent to send an email,
and they must be sent in the correct sequence. As a consequence of this,
executing multiple SMTP.send_message()
tasks in parallel (i.e. with
asyncio.gather()
) is not any more efficient than executing in
sequence, as the client must wait until one mail is sent before beginning the
next.
If you have a lot of emails to send, consider creating multiple connections
(SMTP
instances) and splitting the work between them.
API Reference¶
The send Coroutine¶
-
async
aiosmtplib.
send
(message, sender=None, recipients=None, **kwargs)[source]¶ Send an email message. On await, connects to the SMTP server using the details provided, sends the message, then disconnects.
- Parameters
message – Message text. Either an
email.message.EmailMessage
object,str
orbytes
. If anemail.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
ifuse_tls
isTrue
,587
ifstart_tls
isTrue
, or25
otherwise.username – Username to login as after connect.
password – Password for login after connect.
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.
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.
start_tls – If True, make the initial connection to the server over plaintext, and then upgrade the connection to TLS/SSL. Not compatible 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 withclient_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 or bytes, or a pathlike object in 3.7+.
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
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. Defaults to “localhost”.
port – Server port. Defaults
465
ifuse_tls
isTrue
,587
ifstart_tls
isTrue
, or25
otherwise.username – Username to login as after connect.
password – Password for login after connect.
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 no loop is passed, the running loop will be used. This option is deprecated, and will be removed in future.
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.
start_tls – If True, make the initial connection to the server over plaintext, and then upgrade the connection to TLS/SSL. Not compatible with use_tls.
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 withclient_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 or bytes, or a pathlike object in 3.7+.
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
None
-
async
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
-
async
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
-
async
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
-
close
()¶ Makes sure we reset ESMTP state on close.
- Return type
None
-
async
connect
(**kwargs)¶ 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
ifuse_tls
isTrue
,587
ifstart_tls
isTrue
, or25
otherwise.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 no loop is passed, the running loop will be used. This option is deprecated, and will be removed in future.
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.
start_tls – If True, make the initial connection to the server over plaintext, and then upgrade the connection to TLS/SSL. Not compatible 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 withclient_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 or bytes, or a pathlike object in 3.7+.
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
-
async
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
SMTPDataError – on unexpected server response code
SMTPServerDisconnected – connection lost
- Return type
-
async
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
-
async
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
-
async
expn
(address, options=None, 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
-
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
-
async
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
-
async
help
(timeout=<Default.token: 0>)¶ Send the SMTP HELP command, which responds with help text.
- Raises
SMTPResponseException – on unexpected server response code
- Return type
-
property
is_ehlo_or_helo_needed
¶ Check if we’ve already received a response to an EHLO or HELO command.
- Return type
-
async
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
-
async
mail
(sender, options=None, encoding='ascii', 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
-
async
noop
(timeout=<Default.token: 0>)¶ Send an SMTP NOOP command, which does nothing.
- Raises
SMTPResponseException – on unexpected server response code
- Return type
-
async
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
-
async
rcpt
(recipient, options=None, encoding='ascii', 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
-
async
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
-
async
send_message
(message, sender=None, recipients=None, mail_options=None, rcpt_options=None, timeout=<Default.token: 0>)[source]¶ Sends an
email.message.EmailMessage
object.Arguments are as for
sendmail()
, except that message is anemail.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 usingemail.generator.Generator
andsendmail()
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 the 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: 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
SMTPRecipientsRefused – delivery to all recipients failed
SMTPResponseException – on invalid response
- Return type
Tuple
[Dict
[str
,SMTPResponse
],str
]
-
sendmail_sync
(*args, **kwargs)[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
]
-
property
source_address
¶ Get the system hostname to be sent to the SMTP server. Simply caches the result of
socket.getfqdn()
.- Return type
-
async
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
SMTPException – server does not support STARTTLS
SMTPServerDisconnected – connection lost
ValueError – invalid options provided
- Return type
-
property
supported_auth_methods
¶ Get all AUTH methods supported by the both server and by us.
-
supports_extension
(extension)¶ Tests if the server supports the ESMTP service extension given.
- Return type
-
async
vrfy
(address, options=None, 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
-
Server Responses¶
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¶
-
error_processing
= 451¶
-
help_message
= 214¶
-
insufficient_storage
= 452¶
-
invalid_response
= -1¶
-
mailbox_does_not_exist
= 550¶
-
mailbox_name_invalid
= 553¶
-
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:
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
(message)[source]¶ Bases:
aiosmtplib.errors.SMTPException
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.
-
exception
aiosmtplib.errors.
SMTPConnectTimeoutError
(message)[source]¶ Bases:
aiosmtplib.errors.SMTPTimeoutError
,aiosmtplib.errors.SMTPConnectError
A timeout occurred while connecting to the SMTP server.
-
exception
aiosmtplib.errors.
SMTPReadTimeoutError
(message)[source]¶ Bases:
aiosmtplib.errors.SMTPTimeoutError
A timeout occurred while waiting for a response from the SMTP server.
Changelog¶
1.1.1¶
Bugfix: Fix handling of sending legacy email API (Message) objects.
Bugfix: Fix SMTPNotSupported error with UTF8 sender/recipient names on servers that don’t support SMTPUTF8.
1.1.0¶
Feature: Added send coroutine api.
Feature: Added SMTPUTF8 support for UTF8 chars in addresses.
Feature: Added connected socket and Unix socket path connection options.
Feature: Wait until the connect coroutine is awaited to get the event loop. Passing an explicit event loop via the loop keyword argument is deprecated and will be removed in version 2.0.
Cleanup: Set context for timeout and connection exceptions properly.
Cleanup: Use built in start_tls method on Python 3.7+.
Cleanup: Timeout correctly if TLS handshake takes too long on Python 3.7+.
Cleanup: Updated SMTPProcotol class and removed StreamReader/StreamWriter usage to remove deprecation warnings in 3.8.
Bugfix: EHLO/HELO if required before any command, not just when using higher level commands.
Cleanup: Replaced asserts in functions with more useful errors (e.g. RuntimeError).
Cleanup: More useful error messages for timeouts (thanks ikrivosheev!), including two new exception classes,
SMTPConnectTimeoutError
andSMTPReadTimeoutError
1.0.6¶
Bugfix: Set default timeout to 60 seconds as per documentation (previously it was unlimited).
1.0.5¶
Bugfix: Connection is now closed if an error response is received immediately after connecting.
1.0.4¶
Bugfix: Badly encoded server response messages are now decoded to utf-8, with error chars escaped.
Cleanup: Removed handling for exceptions not raised by asyncio (in SMTPProtocol._readline)
1.0.3¶
Bugfix: Removed buggy close connection on __del__
Bugfix: Fixed old style auth method parsing in ESMTP response.
Bugfix: Cleanup transport on exception in connect method.
Cleanup: Simplified SMTPProtocol.connection_made, __main__
1.0.2¶
Bugfix: Close connection lock on on SMTPServerDisconnected
Feature: Added cert_bundle argument to connection init, connect and starttls methods
Bugfix: Disconnected clients would raise SMTPResponseException: (-1 …) instead of SMTPServerDisconnected
1.0.1¶
Bugfix: Commands were getting out of order when using the client as a context manager within a task
Bugfix: multiple tasks calling connect would get confused
Bugfix: EHLO/HELO responses were being saved even after disconnect
Bugfix: RuntimeError on client cleanup if event loop was closed
Bugfix: CRAM-MD5 auth was not working
Bugfix: AttributeError on STARTTLS under uvloop
1.0.0¶
Initial feature complete release with stable API; future changes will be documented here.