|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import base64 |
| 4 | +from typing import Any |
| 5 | +from urllib.parse import quote |
| 6 | + |
| 7 | +from naas_abi_core.services.email.EmailPorts import ( |
| 8 | + EmailAttachment, |
| 9 | + IEmailAdapter, |
| 10 | + resolve_recipients, |
| 11 | +) |
| 12 | + |
| 13 | +_GRAPH_BASE = "https://graph.microsoft.com/v1.0" |
| 14 | +_SCOPE = ["https://graph.microsoft.com/.default"] |
| 15 | + |
| 16 | + |
| 17 | +class MicrosoftOutlookAdapter(IEmailAdapter): |
| 18 | + """Email adapter that sends via Microsoft Graph API (app-only / client-credentials). |
| 19 | +
|
| 20 | + The sender mailbox is determined by ``from_email`` passed to ``send()``, which |
| 21 | + must be a UPN the registered app has ``Mail.Send`` permission on. |
| 22 | +
|
| 23 | + Limitations: |
| 24 | + - ``from_name`` is accepted for interface compatibility but silently ignored: |
| 25 | + the Graph API always uses the Azure AD display name of the sender mailbox. |
| 26 | + - Attachments must be < 3 MB (Graph API ``fileAttachment`` limit). |
| 27 | + - When both ``html_body`` and ``text_body`` are provided, the HTML body is used. |
| 28 | + The Graph API structured payload does not support multipart/alternative natively. |
| 29 | +
|
| 30 | + Args: |
| 31 | + tenant_id: Azure AD tenant ID. |
| 32 | + client_id: App registration client ID. |
| 33 | + client_secret: App registration client secret. |
| 34 | + user: Default sender mailbox UPN (used when ``from_email`` is absent). |
| 35 | + client: Optional injectable fake for unit tests. Must expose |
| 36 | + ``post(url, payload)`` and ``get_token() -> str``. |
| 37 | + """ |
| 38 | + |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + *, |
| 42 | + tenant_id: str, |
| 43 | + client_id: str, |
| 44 | + client_secret: str, |
| 45 | + user: str, |
| 46 | + client: Any | None = None, |
| 47 | + ) -> None: |
| 48 | + self._tenant_id = tenant_id |
| 49 | + self._client_id = client_id |
| 50 | + self._client_secret = client_secret |
| 51 | + self._user = user |
| 52 | + self._client = client |
| 53 | + self._token: str | None = None |
| 54 | + |
| 55 | + # ── Auth ────────────────────────────────────────────────────────────────── |
| 56 | + |
| 57 | + def _get_token(self) -> str: |
| 58 | + if self._client is not None: |
| 59 | + return self._client.get_token() |
| 60 | + if self._token: |
| 61 | + return self._token |
| 62 | + |
| 63 | + import msal # lazy — optional extra |
| 64 | + |
| 65 | + app = msal.ConfidentialClientApplication( |
| 66 | + client_id=self._client_id, |
| 67 | + authority=f"https://login.microsoftonline.com/{self._tenant_id}", |
| 68 | + client_credential=self._client_secret, |
| 69 | + ) |
| 70 | + result = app.acquire_token_for_client(scopes=_SCOPE) |
| 71 | + if "access_token" not in result: |
| 72 | + raise RuntimeError( |
| 73 | + f"Microsoft Graph token error: {result.get('error')} — " |
| 74 | + f"{result.get('error_description')}" |
| 75 | + ) |
| 76 | + self._token = result["access_token"] |
| 77 | + return self._token |
| 78 | + |
| 79 | + # ── HTTP transport ──────────────────────────────────────────────────────── |
| 80 | + |
| 81 | + def _post(self, url: str, payload: dict[str, Any]) -> None: |
| 82 | + if self._client is not None: |
| 83 | + self._client.post(url, payload) |
| 84 | + return |
| 85 | + |
| 86 | + import requests # lazy |
| 87 | + |
| 88 | + response = requests.post( |
| 89 | + url, |
| 90 | + headers={ |
| 91 | + "Authorization": f"Bearer {self._get_token()}", |
| 92 | + "Content-Type": "application/json", |
| 93 | + }, |
| 94 | + json=payload, |
| 95 | + timeout=30, |
| 96 | + ) |
| 97 | + if response.status_code >= 400: |
| 98 | + detail = response.text.strip() or response.reason |
| 99 | + raise RuntimeError( |
| 100 | + f"Microsoft Graph API request failed ({response.status_code}): {detail}" |
| 101 | + ) |
| 102 | + |
| 103 | + # ── IEmailAdapter ───────────────────────────────────────────────────────── |
| 104 | + |
| 105 | + def send( |
| 106 | + self, |
| 107 | + *, |
| 108 | + to_email: str | None = None, |
| 109 | + subject: str, |
| 110 | + text_body: str, |
| 111 | + html_body: str | None = None, |
| 112 | + from_email: str, |
| 113 | + from_name: str | None = None, |
| 114 | + reply_to: str | None = None, |
| 115 | + attachments: list[EmailAttachment] | None = None, |
| 116 | + to_emails: list[str] | str | None = None, |
| 117 | + ) -> None: |
| 118 | + mailbox = quote(from_email or self._user) |
| 119 | + url = f"{_GRAPH_BASE}/users/{mailbox}/sendMail" |
| 120 | + |
| 121 | + body_payload = ( |
| 122 | + {"contentType": "HTML", "content": html_body} |
| 123 | + if html_body |
| 124 | + else {"contentType": "Text", "content": text_body} |
| 125 | + ) |
| 126 | + |
| 127 | + message: dict[str, Any] = { |
| 128 | + "subject": subject, |
| 129 | + "body": body_payload, |
| 130 | + "toRecipients": [ |
| 131 | + {"emailAddress": {"address": addr}} |
| 132 | + for addr in resolve_recipients(to_email, to_emails) |
| 133 | + ], |
| 134 | + } |
| 135 | + |
| 136 | + if reply_to: |
| 137 | + message["replyTo"] = [{"emailAddress": {"address": reply_to}}] |
| 138 | + |
| 139 | + if attachments: |
| 140 | + message["attachments"] = [ |
| 141 | + { |
| 142 | + "@odata.type": "#microsoft.graph.fileAttachment", |
| 143 | + "name": att.filename, |
| 144 | + "contentType": att.mime_type, |
| 145 | + "contentBytes": base64.b64encode(att.content).decode("ascii"), |
| 146 | + } |
| 147 | + for att in attachments |
| 148 | + ] |
| 149 | + |
| 150 | + self._post(url, {"message": message, "saveToSentItems": True}) |
0 commit comments