Asyncio SMTP Client

5.1.0 · active · verified Mon Apr 06

aiosmtplib is an asynchronous SMTP client for use with asyncio. It provides an async version of Python's `smtplib` module with similar APIs, enabling non-blocking email sending and interaction with SMTP servers. The current version is 5.1.0, and the project actively maintains compatibility with recent Python versions while introducing new features like XOAUTH2 authentication.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates sending an email using the high-level `aiosmtplib.send` coroutine. It uses environment variables for configuration and handles common TLS/STARTTLS scenarios. For more complex interactions or persistent connections, the `SMTP` client class with an `async with` context manager is recommended.

import asyncio
import os
from email.message import EmailMessage
from aiosmtplib import send

async def main():
    sender_email = os.environ.get('SMTP_SENDER_EMAIL', 'sender@example.com')
    recipient_email = os.environ.get('SMTP_RECIPIENT_EMAIL', 'recipient@example.com')
    smtp_host = os.environ.get('SMTP_HOST', 'localhost')
    smtp_port = int(os.environ.get('SMTP_PORT', 25))
    smtp_password = os.environ.get('SMTP_PASSWORD', None)

    message = EmailMessage()
    message['From'] = sender_email
    message['To'] = recipient_email
    message['Subject'] = 'Hello from aiosmtplib!'
    message.set_content('This is a test email sent using aiosmtplib.')

    try:
        await send(
            message,
            hostname=smtp_host,
            port=smtp_port,
            username=sender_email if smtp_password else None,
            password=smtp_password,
            start_tls=True if smtp_port == 587 else False, # Use STARTTLS for common submission port
            use_tls=True if smtp_port == 465 else False # Use direct TLS for common SMTPS port
        )
        print(f"Email sent successfully from {sender_email} to {recipient_email}")
    except Exception as e:
        print(f"Failed to send email: {e}")

if __name__ == '__main__':
    asyncio.run(main())

view raw JSON →