"""Send messages via Microsoft Graph using a stored OAuth refresh token (Mail.Send scope). Mirrors gmail_invite.py's shape exactly so callers can dispatch to either provider interchangeably — see outbound_mail.py. """ from __future__ import annotations import os import httpx from .ms_oauth_utils import MS_TOKEN_URI GRAPH_SEND_MAIL_URL = "https://graph.microsoft.com/v1.0/me/sendMail" async def refresh_access_token(refresh_token: str) -> str: client_id = os.environ.get("MICROSOFT_CLIENT_ID", "").strip() client_secret = os.environ.get("MICROSOFT_CLIENT_SECRET", "").strip() if not client_id or not client_secret: raise ValueError("Microsoft OAuth is not configured") async with httpx.AsyncClient() as client: r = await client.post( MS_TOKEN_URI, data={ "client_id": client_id, "client_secret": client_secret, "refresh_token": refresh_token, "grant_type": "refresh_token", "scope": "https://graph.microsoft.com/Mail.Send offline_access", }, headers={"Content-Type": "application/x-www-form-urlencoded"}, timeout=30.0, ) if r.status_code != 200: raise ValueError(f"Token refresh failed ({r.status_code}): {r.text[:500]}") data = r.json() at = data.get("access_token") if not at: raise ValueError("No access_token in refresh response") return str(at) async def send_invite_email_via_graph( refresh_token: str, from_email: str, to_email: str, subject: str, body: str, ) -> None: """Raises ValueError on configuration or API errors.""" if not from_email or "@" not in from_email: raise ValueError("Inviter has no email address for Microsoft Graph send") access = await refresh_access_token(refresh_token) payload = { "message": { "subject": subject, "body": {"contentType": "Text", "content": body}, "toRecipients": [{"emailAddress": {"address": to_email}}], }, "saveToSentItems": "true", } async with httpx.AsyncClient() as client: r = await client.post( GRAPH_SEND_MAIL_URL, headers={"Authorization": f"Bearer {access}"}, json=payload, timeout=30.0, ) if r.status_code not in (200, 202): err = r.text[:1500] if r.text else "" raise ValueError(f"Microsoft Graph send failed ({r.status_code}): {err}")