| 1 |
.. _oauth: |
| 2 |
|
| 3 |
OAuth2 Authentication (XOAUTH2) |
| 4 |
=============================== |
| 5 |
|
| 6 |
aiosmtplib supports OAuth2 authentication via the XOAUTH2 mechanism, which is |
| 7 |
used by Gmail, Outlook.com, and other providers that have deprecated traditional |
| 8 |
password authentication. |
| 9 |
|
| 10 |
The SMTP server must advertise ``XOAUTH2`` as a supported authentication method. |
| 11 |
|
| 12 |
To use OAuth2, pass an async callable that returns a valid access token to the |
| 13 |
``oauth_token_generator`` parameter. |
| 14 |
|
| 15 |
.. note:: The ``oauth_token_generator`` parameter is mutually exclusive with |
| 16 |
``password``. You cannot use both at the same time. |
| 17 |
|
| 18 |
|
| 19 |
Basic Structure |
| 20 |
--------------- |
| 21 |
|
| 22 |
.. code-block:: python |
| 23 |
|
| 24 |
import aiosmtplib |
| 25 |
|
| 26 |
async def get_access_token() -> str: |
| 27 |
# Your token refresh logic here |
| 28 |
return "your_access_token" |
| 29 |
|
| 30 |
await aiosmtplib.send( |
| 31 |
message, |
| 32 |
hostname="smtp.gmail.com", |
| 33 |
port=465, |
| 34 |
use_tls=True, |
| 35 |
username="[email protected]", |
| 36 |
oauth_token_generator=get_access_token, |
| 37 |
) |
| 38 |
|
| 39 |
|
| 40 |
Token Expiry and Refresh |
| 41 |
------------------------ |
| 42 |
|
| 43 |
OAuth2 access tokens are short-lived (typically 1 hour). The callable passed |
| 44 |
as ``oauth_token_generator`` is responsible for returning a valid, non-expired |
| 45 |
token each time it is called. It will be called immediately before the |
| 46 |
``XOAUTH2`` authentication command is sent to the server. |
| 47 |
|
| 48 |
**Your generator must handle expiry** |
| 49 |
|
| 50 |
aiosmtplib does not track token expiry times or automatically retry on |
| 51 |
authentication failure. Your callable should check if the token is expired |
| 52 |
and refresh it before returning. Some libraries (e.g. ``google-auth``, |
| 53 |
documented below) will handle this. |
| 54 |
|
| 55 |
|
| 56 |
Gmail Example |
| 57 |
------------- |
| 58 |
|
| 59 |
Gmail allows OAuth2 for SMTP access. You'll need to create a project in the |
| 60 |
`Google Cloud Console <https://console.cloud.google.com/>`_, and obtain OAuth2 |
| 61 |
credentials. |
| 62 |
|
| 63 |
The ``google-auth`` library provides credential management with automatic token |
| 64 |
refresh. |
| 65 |
|
| 66 |
.. code-block:: python |
| 67 |
|
| 68 |
import asyncio |
| 69 |
from email.message import EmailMessage |
| 70 |
|
| 71 |
import aiosmtplib |
| 72 |
from google.oauth2.credentials import Credentials |
| 73 |
from google.auth.transport.requests import Request |
| 74 |
|
| 75 |
# Load your credentials (obtained via OAuth flow) |
| 76 |
credentials = Credentials( |
| 77 |
token="ya29.access_token", |
| 78 |
refresh_token="1//refresh_token", |
| 79 |
token_uri="https://oauth2.googleapis.com/token", |
| 80 |
client_id="your_client_id.apps.googleusercontent.com", |
| 81 |
client_secret="your_client_secret", |
| 82 |
) |
| 83 |
|
| 84 |
async def get_gmail_token() -> str: |
| 85 |
"""Return a valid access token, refreshing if needed.""" |
| 86 |
if not credentials.valid: |
| 87 |
# google-auth is synchronous, so run in a thread |
| 88 |
await asyncio.to_thread(credentials.refresh, Request()) |
| 89 |
return credentials.token |
| 90 |
|
| 91 |
async def send_email(): |
| 92 |
message = EmailMessage() |
| 93 |
message["From"] = "[email protected]" |
| 94 |
message["To"] = "[email protected]" |
| 95 |
message["Subject"] = "Hello from aiosmtplib!" |
| 96 |
message.set_content("Sent using OAuth2 authentication.") |
| 97 |
|
| 98 |
await aiosmtplib.send( |
| 99 |
message, |
| 100 |
hostname="smtp.gmail.com", |
| 101 |
port=465, |
| 102 |
use_tls=True, |
| 103 |
username="[email protected]", |
| 104 |
oauth_token_generator=get_gmail_token, |
| 105 |
) |
| 106 |
|
| 107 |
asyncio.run(send_email()) |
| 108 |
|
| 109 |
|
| 110 |
Outlook / Microsoft 365 Example |
| 111 |
------------------------------- |
| 112 |
|
| 113 |
Microsoft requires OAuth2 for SMTP authentication. See the |
| 114 |
`official Microsoft documentation |
| 115 |
<https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth>`_ |
| 116 |
for setup instructions. |
| 117 |
|
| 118 |
The ``msal`` library provides credential management with automatic token |
| 119 |
refresh. |
| 120 |
|
| 121 |
.. code-block:: python |
| 122 |
|
| 123 |
import asyncio |
| 124 |
from email.message import EmailMessage |
| 125 |
|
| 126 |
import aiosmtplib |
| 127 |
import msal |
| 128 |
|
| 129 |
# Your Azure AD app registration details |
| 130 |
CLIENT_ID = "your_client_id" |
| 131 |
TENANT_ID = "your_tenant_id" # Or "common" for multi-tenant apps |
| 132 |
|
| 133 |
# Scope for SMTP sending |
| 134 |
SCOPES = ["https://outlook.office.com/SMTP.Send"] |
| 135 |
|
| 136 |
# Create MSAL public client app (for user authentication) |
| 137 |
app = msal.PublicClientApplication( |
| 138 |
CLIENT_ID, |
| 139 |
authority=f"https://login.microsoftonline.com/{TENANT_ID}", |
| 140 |
) |
| 141 |
|
| 142 |
async def get_outlook_token() -> str: |
| 143 |
"""Return a valid access token, refreshing silently if possible.""" |
| 144 |
accounts = app.get_accounts() |
| 145 |
if accounts: |
| 146 |
# Try to get token silently (uses cached/refresh token) |
| 147 |
result = await asyncio.to_thread( |
| 148 |
app.acquire_token_silent, SCOPES, account=accounts[0] |
| 149 |
) |
| 150 |
if result and "access_token" in result: |
| 151 |
return result["access_token"] |
| 152 |
|
| 153 |
raise ValueError("No valid token available. Re-authentication required.") |
| 154 |
|
| 155 |
async def send_email(): |
| 156 |
message = EmailMessage() |
| 157 |
message["From"] = "[email protected]" |
| 158 |
message["To"] = "[email protected]" |
| 159 |
message["Subject"] = "Hello from aiosmtplib!" |
| 160 |
message.set_content("Sent using OAuth2 authentication.") |
| 161 |
|
| 162 |
await aiosmtplib.send( |
| 163 |
message, |
| 164 |
hostname="smtp.office365.com", |
| 165 |
port=587, |
| 166 |
start_tls=True, |
| 167 |
username="[email protected]", |
| 168 |
oauth_token_generator=get_outlook_token, |
| 169 |
) |
| 170 |
|
| 171 |
asyncio.run(send_email()) |