Python aiosmtplib
last modified November 19, 2026 Python 3.15
In this article we send emails asynchronously in Python with the aiosmtplib library. We test the examples with a local aiosmtpd mail server, and then send real mail through Gmail and the Mailtrap sandbox.
The aiosmtplib library is an asyncio SMTP client. It does
the same job as the standard smtplib module, but its
methods are coroutines, so a program can send many emails at once, or
send email from an asyncio web application, without blocking the event
loop. The messages themselves are built with the standard
email package.
The aiosmtpd library is an asyncio SMTP server. It replaces
the smtpd module, which was removed from the standard
library in Python 3.12. We use it as a local test server that receives
messages and prints them instead of delivering them. The examples were
run with aiosmtplib 5.1 and aiosmtpd 1.4 on Python 3.15.
$ pip install aiosmtplib aiosmtpd
SMTP
Simple Mail Transfer Protocol (SMTP) is the Internet standard for sending email. It was first defined in 1982 by RFC 821; the current version is RFC 5321 from 2008, which includes the Extended SMTP (ESMTP) additions. An email client hands a message to a mail server over SMTP, and mail servers use it to pass the message to each other.
An SMTP session is a text dialog. The client greets the server with
EHLO, names the sender with MAIL FROM, the
recipients with RCPT TO, and sends the message after the
DATA command. The sender and recipients given in these
commands form the envelope; they may differ from the
From, To, and Cc headers inside
the message.
SMTP servers listen on several ports. Port 25 is used between mail
servers. Port 587 is the submission port for clients; the connection
starts as plain text and is upgraded to TLS with the
STARTTLS command. Port 465 is also for clients, but the
connection is encrypted with TLS from the start.
The test mail server
To send an email, we need a mail server. During development we do not want to deliver test messages to real people, so we run a local server. The aiosmtpd package can be started from the command line; by default it uses a debugging handler that prints every received message to the terminal.
The -n option tells the server not to switch to the
nobody user, which needs root rights, and -l
sets the address and port to listen on. We run the server in a separate
terminal and stop it with Ctrl+C. The examples in
the following sections send their messages to it.
$ python -m aiosmtpd -n -l localhost:1025
Sending a simple email
The aiosmtplib.send coroutine is the easiest way to send a
message. It connects to the server, sends the message, and closes the
connection.
import asyncio
from email.message import EmailMessage
import aiosmtplib
async def main():
msg = EmailMessage()
msg['From'] = 'admin@example.com'
msg['To'] = 'info@example.com'
msg['Subject'] = 'Test mail'
msg.set_content('This is a test mail.')
errors, response = await aiosmtplib.send(msg, hostname='localhost', port=1025)
print(f'errors: {errors}')
print(f'response: {response}')
asyncio.run(main())
The example sends a plain text email to the local test server.
msg = EmailMessage()
msg['From'] = 'admin@example.com'
msg['To'] = 'info@example.com'
msg['Subject'] = 'Test mail'
msg.set_content('This is a test mail.')
The message is an EmailMessage from the standard
email package. Headers are set like dictionary items and
the set_content method sets the body. The
example.com domain is reserved for examples in
documentation.
errors, response = await aiosmtplib.send(msg, hostname='localhost', port=1025)
The send coroutine takes the envelope sender and
recipients from the From, To,
Cc, and Bcc headers. It returns a dictionary
of refused recipients and the final response of the server.
The program prints an empty dictionary, because no recipient was
refused, and the OK reply of the server. The aiosmtpd
terminal shows the received message, including the MIME headers added
by EmailMessage and an X-Peer header with the
client address.
$ python simple.py
errors: {}
response: OK
aiosmtpd terminal:
---------- MESSAGE FOLLOWS ----------
mail options: ['BODY=8BITMIME']
From: admin@example.com
To: info@example.com
Subject: Test mail
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
X-Peer: ('127.0.0.1', 56276)
This is a test mail.
------------ END MESSAGE ------------
The SMTP client
The aiosmtplib.SMTP class gives more control over the
connection. Used as an asynchronous context manager, it connects to the
server on entry and sends the QUIT command on exit. One
connection can send several messages.
import asyncio
from email.message import EmailMessage
import aiosmtplib
async def main():
msg = EmailMessage()
msg['From'] = 'admin@example.com'
msg['To'] = 'info@example.com'
msg['Subject'] = 'Test mail'
msg.set_content('This is a test mail.')
async with aiosmtplib.SMTP(hostname='localhost', port=1025) as smtp:
print(f'extensions: {list(smtp.esmtp_extensions)}')
print(f'supports STARTTLS: {smtp.supports_extension("starttls")}')
errors, response = await smtp.send_message(msg)
print(f'response: {response}')
asyncio.run(main())
The example connects to the server, checks the extensions the server supports, and sends a message.
async with aiosmtplib.SMTP(hostname='localhost', port=1025) as smtp:
The client connects and greets the server with EHLO
automatically.
print(f'extensions: {list(smtp.esmtp_extensions)}')
print(f'supports STARTTLS: {smtp.supports_extension("starttls")}')
The esmtp_extensions dictionary holds the extensions the
server announced in its reply to EHLO, and
supports_extension checks for one of them. Our test server
does not offer STARTTLS, because we did not give it a
certificate.
errors, response = await smtp.send_message(msg)
The send_message coroutine sends an
EmailMessage over the open connection.
$ python client.py extensions: ['8bitmime', 'help'] supports STARTTLS: False response: OK
HTML email
An HTML email should also contain a plain text version of the same
content for mail clients that do not display HTML. The two versions are
alternatives of a multipart/alternative message.
import asyncio
from email.message import EmailMessage
import aiosmtplib
text = '''\
Hello,
the new prices are available at https://example.com/prices.
'''
html = '''\
<html>
<body>
<p>Hello,</p>
<p>the new <b>prices</b> are available at
<a href="https://example.com/prices">our website</a>.</p>
</body>
</html>
'''
async def main():
msg = EmailMessage()
msg['From'] = 'admin@example.com'
msg['To'] = 'info@example.com'
msg['Subject'] = 'New prices'
msg.set_content(text)
msg.add_alternative(html, subtype='html')
errors, response = await aiosmtplib.send(msg, hostname='localhost', port=1025)
print(f'response: {response}')
asyncio.run(main())
The example sends an email with a plain text and an HTML body.
msg.set_content(text) msg.add_alternative(html, subtype='html')
The set_content method sets the plain text part and
add_alternative adds the HTML part. The message is
converted to multipart/alternative automatically. Mail
clients pick the last alternative they can display, so the richest
version goes last.
$ python html_mail.py
response: OK
aiosmtpd terminal:
---------- MESSAGE FOLLOWS ----------
mail options: ['BODY=8BITMIME']
From: admin@example.com
To: info@example.com
Subject: New prices
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="===============8878343478987803645=="
X-Peer: ('127.0.0.1', 34748)
--===============8878343478987803645==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
Hello,
the new prices are available at https://example.com/prices.
--===============8878343478987803645==
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
<html>
<body>
<p>Hello,</p>
<p>the new <b>prices</b> are available at
<a href="https://example.com/prices">our website</a>.</p>
</body>
</html>
--===============8878343478987803645==--
------------ END MESSAGE ------------
Sending an attachment
Files are attached with the add_attachment method. In this
example we attach a small text file.
falcon blue sky cloud
The file contains four words, one per line.
import asyncio
import mimetypes
from email.message import EmailMessage
from pathlib import Path
import aiosmtplib
async def main():
msg = EmailMessage()
msg['From'] = 'admin@example.com'
msg['To'] = 'info@example.com'
msg['Subject'] = 'Test mail with attachment'
msg.set_content('The word list is attached.')
path = Path('words.txt')
ctype, _ = mimetypes.guess_type(path)
maintype, subtype = (ctype or 'application/octet-stream').split('/')
msg.add_attachment(path.read_bytes(), maintype=maintype,
subtype=subtype, filename=path.name)
errors, response = await aiosmtplib.send(msg, hostname='localhost', port=1025)
print(f'response: {response}')
asyncio.run(main())
The example sends an email with the words.txt file
attached.
path = Path('words.txt')
ctype, _ = mimetypes.guess_type(path)
maintype, subtype = (ctype or 'application/octet-stream').split('/')
The mimetypes.guess_type function guesses the content type
from the file extension. If it cannot guess, we use the generic
application/octet-stream type.
msg.add_attachment(path.read_bytes(), maintype=maintype,
subtype=subtype, filename=path.name)
The file is read as bytes, so the same code works for images, PDF
documents, or archives. The message becomes
multipart/mixed; the attachment is base64 encoded and gets
a Content-Disposition header with the file name.
$ python attachment.py
response: OK
aiosmtpd terminal:
---------- MESSAGE FOLLOWS ----------
mail options: ['BODY=8BITMIME']
From: admin@example.com
To: info@example.com
Subject: Test mail with attachment
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="===============2411363811092276582=="
X-Peer: ('127.0.0.1', 34758)
--===============2411363811092276582==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
The word list is attached.
--===============2411363811092276582==
Content-Type: text/plain
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="words.txt"
MIME-Version: 1.0
ZmFsY29uCmJsdWUKc2t5CmNsb3VkCg==
--===============2411363811092276582==--
------------ END MESSAGE ------------
Non-ASCII text
Email headers may contain only ASCII characters. The
EmailMessage class encodes other characters automatically,
so we can use any text in the headers and the body.
import asyncio
from email.message import EmailMessage
from email.utils import formataddr
import aiosmtplib
async def main():
msg = EmailMessage()
msg['From'] = formataddr(('Ján Novák', 'jan@example.com'))
msg['To'] = 'info@example.com'
msg['Subject'] = 'Žltá ľalia a čierna káva'
msg.set_content('Príliš žltučký kôň úpěl ďábelské ódy.')
errors, response = await aiosmtplib.send(msg, hostname='localhost', port=1025)
print(f'response: {response}')
asyncio.run(main())
The example sends an email with Slovak and Czech text in the sender name, the subject, and the body.
msg['From'] = formataddr(('Ján Novák', 'jan@example.com'))
The formataddr function from email.utils
creates an address with a display name.
In the received message, the display name and the subject are encoded
as RFC 2047 encoded words. The body is sent as UTF-8 with the
8bit transfer encoding; aiosmtpd shows it decoded.
$ python unicode_mail.py
response: OK
aiosmtpd terminal:
---------- MESSAGE FOLLOWS ----------
mail options: ['BODY=8BITMIME']
From: =?utf-8?q?J=C3=A1n_Nov=C3=A1k?= <jan@example.com>
To: info@example.com
Subject: =?utf-8?b?xb1sdMOhIMS+YWxpYSBhIMSNaWVybmEga8OhdmE=?=
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit
MIME-Version: 1.0
X-Peer: ('127.0.0.1', 34772)
Príliš žltučký kôň úpěl ďábelské ódy.
------------ END MESSAGE ------------
A custom test server
The debugging handler prints whole messages. For the next examples we
write our own aiosmtpd handler, which prints a short summary of each
message, including the envelope recipients, and refuses addresses
outside the example.com domain. Stop the
python -m aiosmtpd server before starting this one; both
use port 1025.
import asyncio
from email import message_from_bytes
from email.policy import default
from aiosmtpd.controller import Controller
class Handler:
async def handle_RCPT(self, server, session, envelope, address, rcpt_options):
if not address.endswith('@example.com'):
return '550 5.1.1 Mailbox unavailable'
envelope.rcpt_tos.append(address)
return '250 OK'
async def handle_DATA(self, server, session, envelope):
msg = message_from_bytes(envelope.content, policy=default)
print(f'from: {envelope.mail_from}')
print(f'to: {", ".join(envelope.rcpt_tos)}')
print(f'subject: {msg["Subject"]}')
print(f'size: {len(envelope.content)} bytes')
print('-' * 30)
return '250 Message accepted'
async def main():
controller = Controller(Handler(), hostname='localhost', port=1025)
controller.start()
print('listening on localhost:1025')
try:
await asyncio.Event().wait()
finally:
controller.stop()
try:
asyncio.run(main())
except KeyboardInterrupt:
pass
A handler is a class whose handle_* coroutines are called
for the SMTP commands.
async def handle_RCPT(self, server, session, envelope, address, rcpt_options):
if not address.endswith('@example.com'):
return '550 5.1.1 Mailbox unavailable'
envelope.rcpt_tos.append(address)
return '250 OK'
The handle_RCPT coroutine is called for every
RCPT TO command. We refuse addresses outside the
example.com domain with the 550 reply code and add the
others to the envelope.
async def handle_DATA(self, server, session, envelope):
msg = message_from_bytes(envelope.content, policy=default)
The handle_DATA coroutine receives the message. We parse
its raw bytes with message_from_bytes to read the subject,
and print the envelope sender and recipients.
controller = Controller(Handler(), hostname='localhost', port=1025) controller.start()
The Controller runs the server in a separate thread. The
main coroutine waits forever until we press
Ctrl+C, and then stops the controller.
$ python server.py listening on localhost:1025
Several recipients
An email can go to several recipients in the To,
Cc, and Bcc headers. Blind carbon copy
recipients receive the message, but must not be visible to the other
recipients.
import asyncio
from email.message import EmailMessage
import aiosmtplib
async def main():
msg = EmailMessage()
msg['From'] = 'admin@example.com'
msg['To'] = 'info@example.com, sales@example.com'
msg['Cc'] = 'manager@example.com'
msg['Bcc'] = 'archive@example.com'
msg['Subject'] = 'Quarterly report'
msg.set_content('The report is ready.')
errors, response = await aiosmtplib.send(msg, hostname='localhost', port=1025)
print(f'response: {response}')
asyncio.run(main())
The example sends a message to two direct recipients, one carbon copy recipient, and one blind carbon copy recipient. Several addresses in one header are separated with commas.
Our custom server shows that all four addresses are in the envelope.
The send coroutine removed the Bcc header
before sending the message, so the other recipients do not see the
archive address. The size of the message is the size of its raw bytes.
$ python recipients.py response: Message accepted server.py terminal: from: admin@example.com to: info@example.com, sales@example.com, manager@example.com, archive@example.com subject: Quarterly report size: 237 bytes ------------------------------
Sending emails concurrently
Because aiosmtplib is asynchronous, we can send many emails at the same time. Mail servers limit the number of connections from one client, so we limit the concurrency with a semaphore.
import asyncio
import time
from email.message import EmailMessage
import aiosmtplib
users = ['john', 'jane', 'peter', 'lucy', 'robert', 'monica']
def create_message(user):
msg = EmailMessage()
msg['From'] = 'admin@example.com'
msg['To'] = f'{user}@example.com'
msg['Subject'] = f'Hello {user}'
msg.set_content(f'Hello {user}, your account is ready.')
return msg
async def send(msg, limit):
async with limit:
errors, response = await aiosmtplib.send(msg, hostname='localhost',
port=1025)
return msg['To'], response
async def main():
limit = asyncio.Semaphore(3)
start = time.perf_counter()
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(send(create_message(user), limit))
for user in users]
for task in tasks:
to, response = task.result()
print(f'{to}: {response}')
elapsed = time.perf_counter() - start
print(f'sent {len(tasks)} emails in {elapsed:.2f} s')
asyncio.run(main())
The example sends a personal message to six users, with at most three connections open at a time.
async with limit:
errors, response = await aiosmtplib.send(msg, hostname='localhost',
port=1025)
return msg['To'], response
Each task waits for the semaphore before it connects. The semaphore allows three tasks in at once; the others wait until a slot is free.
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(send(create_message(user), limit))
for user in users]
The TaskGroup runs the tasks concurrently and waits for all
of them. If one task fails, the group cancels the others and raises the
error in an exception group.
The results are printed in the order of the tasks. The messages may arrive at the server in a different order, and the elapsed time differs between runs.
$ python concurrent_send.py john@example.com: Message accepted jane@example.com: Message accepted peter@example.com: Message accepted lucy@example.com: Message accepted robert@example.com: Message accepted monica@example.com: Message accepted sent 6 emails in 0.01 s
Handling errors
All aiosmtplib exceptions derive from SMTPException. The
more specific ones tell us whether the connection failed, the server
refused the sender or the recipients, or the server did not answer in
time.
import asyncio
from email.message import EmailMessage
import aiosmtplib
def create_message(to):
msg = EmailMessage()
msg['From'] = 'admin@example.com'
msg['To'] = to
msg['Subject'] = 'Test mail'
msg.set_content('This is a test mail.')
return msg
async def send(msg, port):
try:
errors, response = await aiosmtplib.send(msg, hostname='localhost',
port=port, timeout=5)
print(f'sent: {response}')
for address, error in errors.items():
print(f'refused: {address}: {error.code} {error.message}')
except aiosmtplib.SMTPConnectError as e:
print(f'connection failed: {e}')
except aiosmtplib.SMTPRecipientsRefused as e:
print('all recipients refused')
for error in e.recipients:
print(f' {error.recipient}: {error.code} {error.message}')
except aiosmtplib.SMTPException as e:
print(f'SMTP error: {e}')
async def main():
await send(create_message('info@example.com'), 1026)
await send(create_message('info@example.org'), 1025)
await send(create_message('info@example.com, info@example.org'), 1025)
asyncio.run(main())
The example triggers three different outcomes against our custom server.
errors, response = await aiosmtplib.send(msg, hostname='localhost',
port=port, timeout=5)
The timeout parameter limits each network operation to five
seconds; the default is 60 seconds. A server that does not answer in
time raises SMTPTimeoutError.
for address, error in errors.items():
print(f'refused: {address}: {error.code} {error.message}')
If the server refuses only some recipients, the message is still sent to
the others. The refused addresses are returned in the
errors dictionary, so we must check it.
except aiosmtplib.SMTPRecipientsRefused as e:
print('all recipients refused')
for error in e.recipients:
print(f' {error.recipient}: {error.code} {error.message}')
If the server refuses all recipients, the
SMTPRecipientsRefused exception is raised. Its
recipients attribute holds one error per address.
The first message goes to port 1026, where no server listens. The second
is refused, because example.org is not accepted by our
server. The third has two recipients; one of them is refused and the
message is delivered to the other.
$ python errors.py
connection failed: Error connecting to localhost on port 1026: [Errno 111] Connect call failed ('127.0.0.1', 1026)
all recipients refused
info@example.org: 550 5.1.1 Mailbox unavailable
sent: Message accepted
refused: info@example.org: 550 5.1.1 Mailbox unavailable
STARTTLS on a local server
Mail must not travel over the Internet as plain text. With STARTTLS, the client connects in plain text and upgrades the connection to TLS before it logs in or sends the message. To try it locally, we create a self-signed certificate with OpenSSL and give it to aiosmtpd.
$ openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem \
-days 365 -subj '/CN=localhost' -addext 'subjectAltName=DNS:localhost'
$ python -m aiosmtpd -n -l localhost:1025 --tlscert cert.pem --tlskey key.pem
With a certificate, aiosmtpd announces the STARTTLS
extension and, by default, refuses to accept mail on connections that
were not upgraded. A plain client gets the 530 Must issue a
STARTTLS command first reply.
import asyncio
from email.message import EmailMessage
import aiosmtplib
async def main():
msg = EmailMessage()
msg['From'] = 'admin@example.com'
msg['To'] = 'info@example.com'
msg['Subject'] = 'Secured test mail'
msg.set_content('This mail travels over an encrypted connection.')
async with aiosmtplib.SMTP(hostname='localhost', port=1025,
start_tls=True, cert_bundle='cert.pem') as smtp:
tls = smtp.get_transport_info('ssl_object')
print(f'protocol: {tls.version()}')
print(f'cipher: {tls.cipher()[0]}')
errors, response = await smtp.send_message(msg)
print(f'response: {response}')
asyncio.run(main())
The example sends a message over a connection secured with STARTTLS.
async with aiosmtplib.SMTP(hostname='localhost', port=1025,
start_tls=True, cert_bundle='cert.pem') as smtp:
The start_tls=True option upgrades the connection right
after EHLO and raises an error if the server does not
support STARTTLS. The default, None, upgrades only when
the server offers it. Our certificate is not signed by a known
authority, so we tell the client to trust it with
cert_bundle; certificate validation must stay on.
tls = smtp.get_transport_info('ssl_object')
print(f'protocol: {tls.version()}')
print(f'cipher: {tls.cipher()[0]}')
The get_transport_info method returns information about the
underlying connection; the ssl_object tells us the TLS
version and the cipher that were negotiated.
$ python starttls.py protocol: TLSv1.3 cipher: TLS_AES_256_GCM_SHA384 response: OK
Sending email with Gmail
Gmail accepts email from programs through smtp.gmail.com.
We cannot log in with the normal account password; we need an app
password. To create one, turn on 2-Step Verification in the Google
account and generate the password at
myaccount.google.com/apppasswords.
In Google Workspace accounts, an administrator may have disabled app
passwords.
We never write passwords into the source code. The example reads the
address and the app password from environment variables, which we set
in the terminal before running it:
export GMAIL_USER=you@gmail.com and
export GMAIL_APP_PASSWORD=....
import asyncio
import os
from email.message import EmailMessage
import aiosmtplib
async def main():
user = os.environ['GMAIL_USER']
password = os.environ['GMAIL_APP_PASSWORD']
msg = EmailMessage()
msg['From'] = user
msg['To'] = user
msg['Subject'] = 'Test mail from Python'
msg.set_content('This mail was sent with aiosmtplib through Gmail.')
errors, response = await aiosmtplib.send(msg, hostname='smtp.gmail.com',
port=465, use_tls=True, username=user, password=password)
print(f'response: {response}')
asyncio.run(main())
The example sends an email from a Gmail account to the same account.
errors, response = await aiosmtplib.send(msg, hostname='smtp.gmail.com',
port=465, use_tls=True, username=user, password=password)
On port 465, the connection is encrypted from the start, which is
requested with use_tls=True. With the
username and password parameters, the client
logs in before sending. Gmail also supports STARTTLS on port 587; there
we use port=587 and start_tls=True instead of
use_tls.
Gmail always sends the message from the logged-in account; another
From address works only if it is set up as an alias in the
Gmail settings. A personal account can send around 500 messages a day,
so Gmail suits personal scripts and notifications, not newsletters.
Unlike the previous examples, this one sends a real email; check the
inbox of the account.
Testing with Mailtrap
Mailtrap Email Sandbox is an online service that catches test emails. It accepts mail like a real server, but instead of delivering it, it shows the messages in a web inbox, where we can check the headers, the HTML rendering, the attachments, and the spam score. This is useful when an application should be tested against a remote server with authentication and TLS.
After signing up, we find the SMTP credentials under Sandboxes, in the
Integration tab of the sandbox. We store them in the
MAILTRAP_USER and MAILTRAP_PASSWORD
environment variables.
import asyncio
import os
from email.message import EmailMessage
import aiosmtplib
async def main():
user = os.environ['MAILTRAP_USER']
password = os.environ['MAILTRAP_PASSWORD']
msg = EmailMessage()
msg['From'] = 'admin@example.com'
msg['To'] = 'info@example.com'
msg['Subject'] = 'Test mail'
msg.set_content('This mail is caught by the Mailtrap sandbox.')
errors, response = await aiosmtplib.send(msg,
hostname='sandbox.smtp.mailtrap.io', port=2525, start_tls=True,
username=user, password=password)
print(f'response: {response}')
asyncio.run(main())
The example sends a test email to the Mailtrap sandbox.
errors, response = await aiosmtplib.send(msg,
hostname='sandbox.smtp.mailtrap.io', port=2525, start_tls=True,
username=user, password=password)
The sandbox listens on ports 25, 465, 587, and 2525 and supports
STARTTLS. Port 2525 is useful on networks that block the standard mail
ports. The message appears in the sandbox inbox; nothing is delivered
to info@example.com.
Source
In this article we have sent emails asynchronously in Python with the aiosmtplib library and tested them with a local aiosmtpd server. See also the asyncio, aiohttp, socket, and SSL/TLS certificates tutorials.
Author
List all Python tutorials.