aiosmtplib¶
Overview¶
aiosmtplib is an asynchronous SMTP client for use with asyncio.
Quickstart¶
import asyncio
from email.mime.text import MIMEText
import aiosmtplib
loop = asyncio.get_event_loop()
smtp = aiosmtplib.SMTP(hostname="127.0.0.1", port=1025, loop=loop)
loop.run_until_complete(smtp.connect())
message = MIMEText("Sent via aiosmtplib")
message["From"] = "root@localhost"
message["To"] = "somebody@example.com"
message["Subject"] = "Hello World!"
loop.run_until_complete(smtp.send_message(message))
Requirements¶
Python 3.5.2+, compiled with SSL support, is required.
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.
client = SMTP()
loop = asyncio.get_event_loop()
loop.run_until_complete(client.connect(hostname="localhost", port=25))
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()
).
loop = asyncio.get_event_loop()
smtp = aiosmtplib.SMTP(hostname="smtp.gmail.com", port=465, loop=loop, use_tls=True)
loop.run_until_complete(smtp.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.
loop = asyncio.get_event_loop()
smtp = aiosmtplib.SMTP(hostname="smtp.gmail.com", port=587, loop=loop, use_tls=False)
loop.run_until_complete(smtp.connect())
loop.run_until_complete(smtp.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.
async def send_message():
message = MIMEText("Sent via aiosmtplib")
message["From"] = "root@localhost"
message["To"] = "somebody@example.com"
message["Subject"] = "Hello World!"
async with aiosmtplib.SMTP(hostname="127.0.0.1", port=1025, loop=loop):
await smtp.send_message(message)
loop.run_until_complete(send_message())
Sending Messages¶
SMTP.send_message()
¶
This is the simplest API, and is the recommended way to send messages, as it
makes it easy to set headers correctly and handle multi part messages. For
details on creating email.message.Message
objects, see the
stdlib documentation examples.
Use SMTP.send_message()
to send email.message.Message
objects,
including email.mime
subclasses such as
email.mime.text.MIMEText
.
from email.mime.text import MIMEText
message = MIMEText("Sent via aiosmtplib")
message["From"] = "root@localhost"
message["To"] = "somebody@example.com"
message["Subject"] = "Hello World!"
loop = asyncio.get_event_loop()
loop.run_until_complete(smtp.send_message(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"))
loop = asyncio.get_event_loop()
loop.run_until_complete(smtp.send_message(message))
SMTP.sendmail()
¶
Use SMTP.sendmail()
to send raw messages. Note that when using this
method, you must format the message headers yourself.
sender = "root@localhost"
recipients = ["somebody@example.com"]
message = """To: somebody@example.com
From: root@localhost
Subject: Hello World!
Sent via aiosmtplib
"""
loop = asyncio.get_event_loop()
loop.run_until_complete(smtp.sendmail(sender, recipients, message))
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
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.sendmail()
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.
Bug reporting¶
Bug reports (and feature requests) are welcome via Github issues.
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
ifuse_tls
isFalse
,465
ifuse_tls
isTrue
. - 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 withclient_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 ifuse_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 withclient_cert
/client_key
. - cert_bundle – Path to certificate bundle, for TLS verification.
Raises: ValueError – mutually exclusive options provided
Return type:
-
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:
-
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_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 anemail.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 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
- SMTPRecipientsRefused – delivery to all recipients failed
- SMTPResponseException – on invalid response
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: - SMTPRecipientsRefused – delivery to all recipients failed
- SMTPResponseException – on invalid response
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: - SMTPException – server does not support STARTTLS
- SMTPServerDisconnected – connection lost
- ValueError – invalid options provided
Return type:
-
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¶
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¶
-
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.
Changelog¶
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 recieved 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 ESMPT 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.