#!/usr/bin/env python3 """Verify SMTP connectivity and authentication without sending email.""" import os import smtplib import ssl import sys from pathlib import Path REQUIRED_SETTINGS = ("MAIL_HOST", "MAIL_PORT", "MAIL_USERNAME", "MAIL_PASSWORD", "MAIL_FROM") def load_dotenv(path): if not path.is_file(): raise RuntimeError("Missing .env. Copy .env.example to .env and enter the SMTP settings.") for line in path.read_text(encoding="utf-8").splitlines(): line = line.strip() if not line or line.startswith("#"): continue key, separator, value = line.partition("=") if separator and key.strip(): os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'")) def main(): project_root = Path(__file__).resolve().parent.parent load_dotenv(project_root / ".env") missing = [setting for setting in REQUIRED_SETTINGS if not os.environ.get(setting)] if missing: raise RuntimeError(f"Missing required SMTP settings: {', '.join(missing)}") host = os.environ["MAIL_HOST"] port = int(os.environ["MAIL_PORT"]) username = os.environ["MAIL_USERNAME"] password = os.environ["MAIL_PASSWORD"] context = ssl.create_default_context() try: with smtplib.SMTP(host, port, timeout=15) as client: client.ehlo() client.starttls(context=context) client.ehlo() client.login(username, password) except (OSError, smtplib.SMTPException) as error: print(f"SMTP_CONNECTION_FAILED: {error}", file=sys.stderr) return 1 print(f"SMTP_CONNECTION_OK: {host}:{port} authenticated as {username}") return 0 if __name__ == "__main__": try: raise SystemExit(main()) except (RuntimeError, ValueError) as error: print(f"SMTP_CONFIGURATION_ERROR: {error}", file=sys.stderr) raise SystemExit(2)