| 1 |
#!/usr/bin/env python3 |
| 2 |
# /// script |
| 3 |
# requires-python = ">=3.9" |
| 4 |
# dependencies = [ |
| 5 |
# "aiosmtplib", |
| 6 |
# "google-auth", |
| 7 |
# "google-auth-oauthlib", |
| 8 |
# ] |
| 9 |
# |
| 10 |
# [tool.uv.sources] |
| 11 |
# aiosmtplib = { path = ".." } |
| 12 |
# /// |
| 13 |
""" |
| 14 |
Test script for Gmail XOAUTH2 authentication with aiosmtplib. |
| 15 |
|
| 16 |
Usage: |
| 17 |
# Step 1: Get a refresh token (one-time setup) |
| 18 |
python test_gmail_oauth.py authorize \ |
| 19 |
--client-id YOUR_CLIENT_ID \ |
| 20 |
--client-secret YOUR_CLIENT_SECRET |
| 21 |
|
| 22 |
# Step 2: Send a test email |
| 23 |
python test_gmail_oauth.py send \ |
| 24 |
--client-id YOUR_CLIENT_ID \ |
| 25 |
--client-secret YOUR_CLIENT_SECRET \ |
| 26 |
--refresh-token YOUR_REFRESH_TOKEN \ |
| 27 |
--username [email protected] \ |
| 28 |
--to [email protected] |
| 29 |
|
| 30 |
This script will send a test email using Gmail's SMTP server with OAuth2 |
| 31 |
authentication. |
| 32 |
|
| 33 |
Run with: uv run test_gmail_oauth.py <command> [options] |
| 34 |
""" |
| 35 |
|
| 36 |
import argparse |
| 37 |
import asyncio |
| 38 |
from email.message import EmailMessage |
| 39 |
|
| 40 |
from google.auth.transport.requests import Request |
| 41 |
from google.oauth2.credentials import Credentials |
| 42 |
from google_auth_oauthlib.flow import InstalledAppFlow |
| 43 |
|
| 44 |
import aiosmtplib |
| 45 |
|
| 46 |
# Gmail SMTP scope |
| 47 |
GMAIL_SCOPES = ["https://mail.google.com/"] |
| 48 |
|
| 49 |
# Google OAuth2 token endpoint |
| 50 |
TOKEN_URI = "https://oauth2.googleapis.com/token" |
| 51 |
|
| 52 |
|
| 53 |
def authorize(client_id: str, client_secret: str) -> None: |
| 54 |
"""Run the OAuth2 authorization flow to get a refresh token.""" |
| 55 |
# Build client config for InstalledAppFlow |
| 56 |
client_config = { |
| 57 |
"installed": { |
| 58 |
"client_id": client_id, |
| 59 |
"client_secret": client_secret, |
| 60 |
"auth_uri": "https://accounts.google.com/o/oauth2/auth", |
| 61 |
"token_uri": TOKEN_URI, |
| 62 |
"redirect_uris": ["http://localhost"], |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
flow = InstalledAppFlow.from_client_config(client_config, scopes=GMAIL_SCOPES) |
| 67 |
|
| 68 |
print("=" * 60) |
| 69 |
print("Gmail OAuth2 Authorization") |
| 70 |
print("=" * 60) |
| 71 |
print() |
| 72 |
print("Opening browser for authorization...") |
| 73 |
|
| 74 |
credentials = flow.run_local_server(port=8089) |
| 75 |
|
| 76 |
print() |
| 77 |
print("=" * 60) |
| 78 |
print("Authorization successful!") |
| 79 |
print("=" * 60) |
| 80 |
print() |
| 81 |
print(f"Access Token: {credentials.token[:50]}...") |
| 82 |
print(f"Refresh Token: {credentials.refresh_token}") |
| 83 |
print(f"Expiry: {credentials.expiry}") |
| 84 |
print() |
| 85 |
print("Save the refresh token above and use it with the 'send' command.") |
| 86 |
|
| 87 |
|
| 88 |
async def send_test_email( |
| 89 |
client_id: str, |
| 90 |
client_secret: str, |
| 91 |
refresh_token: str, |
| 92 |
username: str, |
| 93 |
to: str, |
| 94 |
) -> None: |
| 95 |
"""Send a test email using Gmail XOAUTH2.""" |
| 96 |
# Create credentials object using google-auth |
| 97 |
credentials = Credentials( |
| 98 |
token=None, # Will be refreshed |
| 99 |
refresh_token=refresh_token, |
| 100 |
token_uri=TOKEN_URI, |
| 101 |
client_id=client_id, |
| 102 |
client_secret=client_secret, |
| 103 |
) |
| 104 |
|
| 105 |
async def get_gmail_token() -> str: |
| 106 |
"""Return a valid access token, refreshing if needed.""" |
| 107 |
if not credentials.valid: |
| 108 |
print("Refreshing access token...") |
| 109 |
await asyncio.to_thread(credentials.refresh, Request()) |
| 110 |
print(f"Got access token: {credentials.token[:20]}...") |
| 111 |
return credentials.token |
| 112 |
|
| 113 |
# Build the email message |
| 114 |
message = EmailMessage() |
| 115 |
message["From"] = username |
| 116 |
message["To"] = to |
| 117 |
message["Subject"] = "Test email from aiosmtplib XOAUTH2" |
| 118 |
message.set_content( |
| 119 |
"This is a test email sent using aiosmtplib with Gmail XOAUTH2 authentication.\n\n" |
| 120 |
"If you received this, the OAuth2 implementation is working correctly!" |
| 121 |
) |
| 122 |
|
| 123 |
print(f"Sending email from {username} to {to}...") |
| 124 |
|
| 125 |
# Send via Gmail SMTP with OAuth2 |
| 126 |
response = await aiosmtplib.send( |
| 127 |
message, |
| 128 |
hostname="smtp.gmail.com", |
| 129 |
port=465, |
| 130 |
use_tls=True, |
| 131 |
username=username, |
| 132 |
oauth_token_generator=get_gmail_token, |
| 133 |
) |
| 134 |
|
| 135 |
print("Email sent successfully!") |
| 136 |
print(f"Server response: {response}") |
| 137 |
|
| 138 |
|
| 139 |
def main() -> None: |
| 140 |
parser = argparse.ArgumentParser(description="Test Gmail XOAUTH2 with aiosmtplib") |
| 141 |
subparsers = parser.add_subparsers(dest="command", required=True) |
| 142 |
|
| 143 |
# Authorize subcommand |
| 144 |
auth_parser = subparsers.add_parser( |
| 145 |
"authorize", |
| 146 |
help="Get a refresh token via OAuth2 authorization flow", |
| 147 |
) |
| 148 |
auth_parser.add_argument( |
| 149 |
"--client-id", |
| 150 |
required=True, |
| 151 |
help="Google OAuth2 client ID", |
| 152 |
) |
| 153 |
auth_parser.add_argument( |
| 154 |
"--client-secret", |
| 155 |
required=True, |
| 156 |
help="Google OAuth2 client secret", |
| 157 |
) |
| 158 |
|
| 159 |
# Send subcommand |
| 160 |
send_parser = subparsers.add_parser( |
| 161 |
"send", |
| 162 |
help="Send a test email using OAuth2", |
| 163 |
) |
| 164 |
send_parser.add_argument( |
| 165 |
"--client-id", |
| 166 |
required=True, |
| 167 |
help="Google OAuth2 client ID", |
| 168 |
) |
| 169 |
send_parser.add_argument( |
| 170 |
"--client-secret", |
| 171 |
required=True, |
| 172 |
help="Google OAuth2 client secret", |
| 173 |
) |
| 174 |
send_parser.add_argument( |
| 175 |
"--refresh-token", |
| 176 |
required=True, |
| 177 |
help="Google OAuth2 refresh token", |
| 178 |
) |
| 179 |
send_parser.add_argument( |
| 180 |
"--username", |
| 181 |
required=True, |
| 182 |
help="Sender email address (your Gmail address)", |
| 183 |
) |
| 184 |
send_parser.add_argument( |
| 185 |
"--to", |
| 186 |
required=True, |
| 187 |
help="Recipient email address", |
| 188 |
) |
| 189 |
|
| 190 |
args = parser.parse_args() |
| 191 |
|
| 192 |
if args.command == "authorize": |
| 193 |
authorize(args.client_id, args.client_secret) |
| 194 |
elif args.command == "send": |
| 195 |
asyncio.run( |
| 196 |
send_test_email( |
| 197 |
client_id=args.client_id, |
| 198 |
client_secret=args.client_secret, |
| 199 |
refresh_token=args.refresh_token, |
| 200 |
username=args.username, |
| 201 |
to=args.to, |
| 202 |
) |
| 203 |
) |
| 204 |
|
| 205 |
|
| 206 |
if __name__ == "__main__": |
| 207 |
main() |