flowbox 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. {flowbox-0.2.0/src/flowbox.egg-info → flowbox-0.3.0}/PKG-INFO +40 -11
  2. {flowbox-0.2.0 → flowbox-0.3.0}/README.md +38 -9
  3. {flowbox-0.2.0 → flowbox-0.3.0}/pyproject.toml +3 -3
  4. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox/_flowbox.py +18 -0
  5. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox/adapters/__init__.py +2 -0
  6. flowbox-0.3.0/src/flowbox/adapters/_microsoft_graph.py +310 -0
  7. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox/settings/_settings.py +31 -0
  8. {flowbox-0.2.0 → flowbox-0.3.0/src/flowbox.egg-info}/PKG-INFO +40 -11
  9. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox.egg-info/SOURCES.txt +2 -0
  10. flowbox-0.3.0/tests/test_microsoft_graph.py +269 -0
  11. {flowbox-0.2.0 → flowbox-0.3.0}/tests/test_settings.py +34 -1
  12. {flowbox-0.2.0 → flowbox-0.3.0}/LICENSE +0 -0
  13. {flowbox-0.2.0 → flowbox-0.3.0}/setup.cfg +0 -0
  14. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox/__init__.py +0 -0
  15. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox/_exceptions.py +0 -0
  16. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox/_message.py +0 -0
  17. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox/_mime.py +0 -0
  18. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox/adapters/_abc.py +0 -0
  19. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox/adapters/_imap.py +0 -0
  20. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox/adapters/_lettermint.py +0 -0
  21. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox/adapters/_log.py +0 -0
  22. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox/adapters/_smtp.py +0 -0
  23. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox/py.typed +0 -0
  24. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox/settings/__init__.py +0 -0
  25. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox.egg-info/dependency_links.txt +0 -0
  26. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox.egg-info/requires.txt +0 -0
  27. {flowbox-0.2.0 → flowbox-0.3.0}/src/flowbox.egg-info/top_level.txt +0 -0
  28. {flowbox-0.2.0 → flowbox-0.3.0}/tests/test_boundary.py +0 -0
  29. {flowbox-0.2.0 → flowbox-0.3.0}/tests/test_flowbox.py +0 -0
  30. {flowbox-0.2.0 → flowbox-0.3.0}/tests/test_imap.py +0 -0
  31. {flowbox-0.2.0 → flowbox-0.3.0}/tests/test_lettermint.py +0 -0
  32. {flowbox-0.2.0 → flowbox-0.3.0}/tests/test_mime.py +0 -0
  33. {flowbox-0.2.0 → flowbox-0.3.0}/tests/test_smtp.py +0 -0
  34. {flowbox-0.2.0 → flowbox-0.3.0}/tests/test_typing.py +0 -0
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flowbox
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: A vendor-neutral email connector: read inboxes and send mail through the adapter you choose.
5
5
  Author: Flowmatic, UniForceMusic
6
6
  License-Expression: MIT
7
7
  Project-URL: Homepage, https://github.com/Flowmatic-AI/flowmatic-toolkit
8
8
  Project-URL: Repository, https://github.com/Flowmatic-AI/flowmatic-toolkit
9
9
  Project-URL: Issues, https://github.com/Flowmatic-AI/flowmatic-toolkit/issues
10
- Keywords: email,mail,inbox,outbox,smtp,imap,lettermint
10
+ Keywords: email,mail,inbox,outbox,smtp,imap,lettermint,microsoft-graph,exchange
11
11
  Classifier: Development Status :: 2 - Pre-Alpha
12
12
  Classifier: Intended Audience :: Developers
13
13
  Classifier: Programming Language :: Python :: 3
@@ -34,12 +34,13 @@ A vendor-neutral email connector: read inboxes and send mail through the adapter
34
34
 
35
35
  [`../project`](../project) is a small flowlab app that shows how to wire it into an application: settings, one factory module, a queued send job, polling and a webhook route.
36
36
 
37
- | Adapter | Inbox | Webhooks | Outbox |
38
- |---------------------|:-----:|:--------:|:------:|
39
- | `IMAPAdapter` | ✓ | | |
40
- | `SMTPAdapter` | | | ✓ |
41
- | `LettermintAdapter` | ✓ | ✓ | ✓ |
42
- | `LogAdapter` | | | ✓ |
37
+ | Adapter | Inbox | Webhooks | Outbox |
38
+ |-------------------------|:-----:|:--------:|:------:|
39
+ | `IMAPAdapter` | ✓ | | |
40
+ | `SMTPAdapter` | | | ✓ |
41
+ | `LettermintAdapter` | ✓ | ✓ | ✓ |
42
+ | `MicrosoftGraphAdapter` | | | ✓ |
43
+ | `LogAdapter` | | | ✓ |
43
44
 
44
45
  `LogAdapter` sends nothing; it logs each message on the `flowbox.log` logger, like Laravel's log mailer. Use it for local work, not production.
45
46
 
@@ -72,7 +73,7 @@ Each `outbox()` / `inbox()` call builds a new flow: open one per job, command or
72
73
 
73
74
  | Variable | Default | Used for |
74
75
  |---|---|---|
75
- | `MAIL_OUTBOX` | `log` | `log`, `smtp` or `lettermint` |
76
+ | `MAIL_OUTBOX` | `log` | `log`, `smtp`, `lettermint` or `graph` |
76
77
  | `MAIL_INBOX` | unset | `imap` or `lettermint`; unset when the app reads no mail |
77
78
  | `MAIL_FROM_ADDRESS`, `MAIL_FROM_NAME` | unset | The sender of messages that set none |
78
79
  | `MAIL_TIMEOUT` | `30` | Seconds before a provider call gives up |
@@ -83,6 +84,9 @@ Each `outbox()` / `inbox()` call builds a new flow: open one per job, command or
83
84
  | `LETTERMINT_PROJECT_TOKEN`, `LETTERMINT_ROUTE` | | `MAIL_OUTBOX=lettermint` |
84
85
  | `LETTERMINT_TEAM_TOKEN`, `LETTERMINT_PROJECT_ID` | | `MAIL_INBOX=lettermint` |
85
86
  | `LETTERMINT_WEBHOOK_SECRET` | | `settings.lettermint_webhooks()` |
87
+ | `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET` | | `MAIL_OUTBOX=graph` |
88
+ | `GRAPH_SENDER` | `MAIL_FROM_ADDRESS` | The mailbox Graph sends as |
89
+ | `GRAPH_SAVE_TO_SENT_ITEMS` | `true` | Keep a copy in the mailbox's Sent Items |
86
90
 
87
91
  Webhooks stay per vendor: `settings.lettermint_webhooks()` returns a `FlowInbox[LettermintAdapter]` for that vendor's webhook route. Your own adapter goes in by overriding `outbox_adapter()` or `inbox_adapter()`:
88
92
 
@@ -118,12 +122,12 @@ with FlowOutbox.connect_smtp("smtp.example.com", "user", "secret", sender=Addres
118
122
 
119
123
  A few `Message` fields are for providers that support them; an adapter whose provider has no equivalent ignores them.
120
124
 
121
- | Field | Lettermint | SMTP |
125
+ | Field | Lettermint | SMTP, Microsoft Graph |
122
126
  |---|---|---|
123
127
  | `idempotency_key` | `Idempotency-Key`: the same key is sent once, so retrying after an uncertain failure cannot send twice | ignored |
124
128
  | `tag`, `metadata` | stored with the message, returned in delivery webhooks | ignored |
125
129
  | `track_opens`, `track_clicks` | per-message tracking; `None` keeps the project default | ignored |
126
- | `require_tls` | `tls: enforced` | ignored; the connection's own `encryption` applies |
130
+ | `require_tls` | `tls: enforced` | ignored; SMTP's own `encryption` applies |
127
131
 
128
132
  ### Errors
129
133
 
@@ -195,3 +199,28 @@ lettermint = LettermintAdapter(project_token="lm_...", team_token="lm_team_...",
195
199
  inbox = FlowInbox(lettermint)
196
200
  outbox = FlowOutbox(lettermint, sender=Address("noreply@acme.com"))
197
201
  ```
202
+
203
+ ## Microsoft Graph
204
+
205
+ Sends as an Exchange Online mailbox (`fleet@acme.com`, say) with the client credentials of an Entra app registration, instead of SMTP:
206
+
207
+ ```python
208
+ from flowbox import Address, FlowOutbox
209
+
210
+ outbox = FlowOutbox.connect_microsoft_graph(
211
+ tenant_id="...",
212
+ client_id="...",
213
+ client_secret="...",
214
+ mailbox="fleet@acme.com",
215
+ sender=Address("fleet@acme.com", "Fleet"),
216
+ )
217
+ ```
218
+
219
+ The app needs the right to send as that mailbox. Either grant the `Mail.Send` application permission (every mailbox in the tenant), or have the tenant's admin scope it to the one mailbox with **Exchange Online Application RBAC** ("Application Mail.Send"). With RBAC the token carries no `Mail.Send` role; that is expected, Exchange does the check.
220
+
221
+ - Without `mailbox`, each message's sender is the mailbox. A sender other than the mailbox goes in `from`, which needs Send As or Send on Behalf rights on that address.
222
+ - Attachments up to ~2.9 MB together go inline with `sendMail` (Graph caps a request at 4 MB). Larger ones go through a draft and upload sessions, which also needs `Mail.ReadWrite` ("Application Mail.ReadWrite"); if an upload fails, the draft is deleted.
223
+ - `sendMail` returns no id, so `send_mail()` sets the internet message id itself and returns it, like SMTP's `Message-ID`; a `Message-ID` in `message.headers` is kept.
224
+ - Graph only accepts custom headers that start with `X-`; other headers are left out.
225
+ - Tokens are cached in the process until five minutes before they expire, shared by every adapter with the same credentials. A cached token Graph refuses is replaced once.
226
+ - A failed token request raises an `AdapterError` with Entra's reason (`AADSTS7000215: Invalid client secret provided.`), never the secret.
@@ -4,12 +4,13 @@ A vendor-neutral email connector: read inboxes and send mail through the adapter
4
4
 
5
5
  [`../project`](../project) is a small flowlab app that shows how to wire it into an application: settings, one factory module, a queued send job, polling and a webhook route.
6
6
 
7
- | Adapter | Inbox | Webhooks | Outbox |
8
- |---------------------|:-----:|:--------:|:------:|
9
- | `IMAPAdapter` | ✓ | | |
10
- | `SMTPAdapter` | | | ✓ |
11
- | `LettermintAdapter` | ✓ | ✓ | ✓ |
12
- | `LogAdapter` | | | ✓ |
7
+ | Adapter | Inbox | Webhooks | Outbox |
8
+ |-------------------------|:-----:|:--------:|:------:|
9
+ | `IMAPAdapter` | ✓ | | |
10
+ | `SMTPAdapter` | | | ✓ |
11
+ | `LettermintAdapter` | ✓ | ✓ | ✓ |
12
+ | `MicrosoftGraphAdapter` | | | ✓ |
13
+ | `LogAdapter` | | | ✓ |
13
14
 
14
15
  `LogAdapter` sends nothing; it logs each message on the `flowbox.log` logger, like Laravel's log mailer. Use it for local work, not production.
15
16
 
@@ -42,7 +43,7 @@ Each `outbox()` / `inbox()` call builds a new flow: open one per job, command or
42
43
 
43
44
  | Variable | Default | Used for |
44
45
  |---|---|---|
45
- | `MAIL_OUTBOX` | `log` | `log`, `smtp` or `lettermint` |
46
+ | `MAIL_OUTBOX` | `log` | `log`, `smtp`, `lettermint` or `graph` |
46
47
  | `MAIL_INBOX` | unset | `imap` or `lettermint`; unset when the app reads no mail |
47
48
  | `MAIL_FROM_ADDRESS`, `MAIL_FROM_NAME` | unset | The sender of messages that set none |
48
49
  | `MAIL_TIMEOUT` | `30` | Seconds before a provider call gives up |
@@ -53,6 +54,9 @@ Each `outbox()` / `inbox()` call builds a new flow: open one per job, command or
53
54
  | `LETTERMINT_PROJECT_TOKEN`, `LETTERMINT_ROUTE` | | `MAIL_OUTBOX=lettermint` |
54
55
  | `LETTERMINT_TEAM_TOKEN`, `LETTERMINT_PROJECT_ID` | | `MAIL_INBOX=lettermint` |
55
56
  | `LETTERMINT_WEBHOOK_SECRET` | | `settings.lettermint_webhooks()` |
57
+ | `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET` | | `MAIL_OUTBOX=graph` |
58
+ | `GRAPH_SENDER` | `MAIL_FROM_ADDRESS` | The mailbox Graph sends as |
59
+ | `GRAPH_SAVE_TO_SENT_ITEMS` | `true` | Keep a copy in the mailbox's Sent Items |
56
60
 
57
61
  Webhooks stay per vendor: `settings.lettermint_webhooks()` returns a `FlowInbox[LettermintAdapter]` for that vendor's webhook route. Your own adapter goes in by overriding `outbox_adapter()` or `inbox_adapter()`:
58
62
 
@@ -88,12 +92,12 @@ with FlowOutbox.connect_smtp("smtp.example.com", "user", "secret", sender=Addres
88
92
 
89
93
  A few `Message` fields are for providers that support them; an adapter whose provider has no equivalent ignores them.
90
94
 
91
- | Field | Lettermint | SMTP |
95
+ | Field | Lettermint | SMTP, Microsoft Graph |
92
96
  |---|---|---|
93
97
  | `idempotency_key` | `Idempotency-Key`: the same key is sent once, so retrying after an uncertain failure cannot send twice | ignored |
94
98
  | `tag`, `metadata` | stored with the message, returned in delivery webhooks | ignored |
95
99
  | `track_opens`, `track_clicks` | per-message tracking; `None` keeps the project default | ignored |
96
- | `require_tls` | `tls: enforced` | ignored; the connection's own `encryption` applies |
100
+ | `require_tls` | `tls: enforced` | ignored; SMTP's own `encryption` applies |
97
101
 
98
102
  ### Errors
99
103
 
@@ -165,3 +169,28 @@ lettermint = LettermintAdapter(project_token="lm_...", team_token="lm_team_...",
165
169
  inbox = FlowInbox(lettermint)
166
170
  outbox = FlowOutbox(lettermint, sender=Address("noreply@acme.com"))
167
171
  ```
172
+
173
+ ## Microsoft Graph
174
+
175
+ Sends as an Exchange Online mailbox (`fleet@acme.com`, say) with the client credentials of an Entra app registration, instead of SMTP:
176
+
177
+ ```python
178
+ from flowbox import Address, FlowOutbox
179
+
180
+ outbox = FlowOutbox.connect_microsoft_graph(
181
+ tenant_id="...",
182
+ client_id="...",
183
+ client_secret="...",
184
+ mailbox="fleet@acme.com",
185
+ sender=Address("fleet@acme.com", "Fleet"),
186
+ )
187
+ ```
188
+
189
+ The app needs the right to send as that mailbox. Either grant the `Mail.Send` application permission (every mailbox in the tenant), or have the tenant's admin scope it to the one mailbox with **Exchange Online Application RBAC** ("Application Mail.Send"). With RBAC the token carries no `Mail.Send` role; that is expected, Exchange does the check.
190
+
191
+ - Without `mailbox`, each message's sender is the mailbox. A sender other than the mailbox goes in `from`, which needs Send As or Send on Behalf rights on that address.
192
+ - Attachments up to ~2.9 MB together go inline with `sendMail` (Graph caps a request at 4 MB). Larger ones go through a draft and upload sessions, which also needs `Mail.ReadWrite` ("Application Mail.ReadWrite"); if an upload fails, the draft is deleted.
193
+ - `sendMail` returns no id, so `send_mail()` sets the internet message id itself and returns it, like SMTP's `Message-ID`; a `Message-ID` in `message.headers` is kept.
194
+ - Graph only accepts custom headers that start with `X-`; other headers are left out.
195
+ - Tokens are cached in the process until five minutes before they expire, shared by every adapter with the same credentials. A cached token Graph refuses is replaced once.
196
+ - A failed token request raises an `AdapterError` with Entra's reason (`AADSTS7000215: Invalid client secret provided.`), never the secret.
@@ -4,13 +4,13 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "flowbox"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "A vendor-neutral email connector: read inboxes and send mail through the adapter you choose."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.14"
11
11
  license = "MIT"
12
12
  license-files = ["LICENSE"]
13
- keywords = ["email", "mail", "inbox", "outbox", "smtp", "imap", "lettermint"]
13
+ keywords = ["email", "mail", "inbox", "outbox", "smtp", "imap", "lettermint", "microsoft-graph", "exchange"]
14
14
 
15
15
  authors = [
16
16
  {name = "Flowmatic"},
@@ -26,7 +26,7 @@ classifiers = [
26
26
  "Typing :: Typed",
27
27
  ]
28
28
 
29
- # Standard library only, Lettermint included: its API is plain JSON over HTTPS.
29
+ # Standard library only, Lettermint and Microsoft Graph included: their APIs are plain JSON over HTTPS.
30
30
  # flowbox.settings, which reads the environment, is the one extra.
31
31
  dependencies = []
32
32
 
@@ -130,6 +130,24 @@ class FlowOutbox:
130
130
 
131
131
  return cls(LettermintAdapter(project_token=project_token, route=route, timeout=timeout), sender)
132
132
 
133
+ @classmethod
134
+ def connect_microsoft_graph(
135
+ cls,
136
+ tenant_id: str,
137
+ client_id: str,
138
+ client_secret: str,
139
+ mailbox: str | None = None,
140
+ sender: Address | None = None,
141
+ save_to_sent_items: bool = True,
142
+ timeout: float = 30.0,
143
+ ) -> Self:
144
+ """Sends as ``mailbox`` (the sender's address when unset) with an Entra
145
+ app registration's client credentials."""
146
+ from flowbox.adapters import MicrosoftGraphAdapter
147
+
148
+ adapter = MicrosoftGraphAdapter(tenant_id, client_id, client_secret, mailbox, save_to_sent_items, timeout)
149
+ return cls(adapter, sender)
150
+
133
151
  @property
134
152
  def adapter(self) -> OutboxAdapterABC:
135
153
  return self._adapter
@@ -8,6 +8,7 @@ from flowbox.adapters._abc import (
8
8
  from flowbox.adapters._imap import IMAPAdapter
9
9
  from flowbox.adapters._lettermint import LettermintAdapter
10
10
  from flowbox.adapters._log import LogAdapter
11
+ from flowbox.adapters._microsoft_graph import MicrosoftGraphAdapter
11
12
  from flowbox.adapters._smtp import SMTPAdapter
12
13
 
13
14
  __all__ = [
@@ -17,6 +18,7 @@ __all__ = [
17
18
  "InboxAdapterABC",
18
19
  "LettermintAdapter",
19
20
  "LogAdapter",
21
+ "MicrosoftGraphAdapter",
20
22
  "OutboxAdapterABC",
21
23
  "SMTPAdapter",
22
24
  "WebhookInboxAdapterABC",
@@ -0,0 +1,310 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import hashlib
5
+ import json
6
+ import threading
7
+ import time
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from email.utils import make_msgid
12
+ from typing import Any
13
+
14
+ from flowbox._exceptions import AdapterError
15
+ from flowbox._message import Address, Attachment, Message
16
+ from flowbox.adapters._abc import OutboxAdapterABC, require_sender
17
+
18
+ _GRAPH_URL = "https://graph.microsoft.com/v1.0"
19
+ _LOGIN_URL = "https://login.microsoftonline.com"
20
+
21
+ #: A sendMail request may be at most 4 MB, and base64 grows a file by a third.
22
+ #: Attachments above this, together, go through a draft and upload sessions.
23
+ INLINE_ATTACHMENT_LIMIT_BYTES = 2_900_000
24
+
25
+ #: Upload-session chunks must be a multiple of 320 KiB.
26
+ _UPLOAD_CHUNK_BYTES = 320 * 1024 * 10
27
+
28
+ #: Tokens are shared by every adapter with the same app credentials, so a new
29
+ #: adapter per job does not fetch a new token per job.
30
+ _tokens: dict[tuple[str, str, str], tuple[str, float]] = {}
31
+ _tokens_lock = threading.Lock()
32
+
33
+
34
+ def _transient(status_code: int | None) -> bool:
35
+ return status_code is None or status_code == 429 or status_code >= 500
36
+
37
+
38
+ def _recipients(addresses: list[Address]) -> list[dict[str, Any]]:
39
+ return [
40
+ {"emailAddress": {"address": address.email, **({"name": address.name} if address.name else {})}}
41
+ for address in addresses
42
+ ]
43
+
44
+
45
+ def _attachment_payload(attachment: Attachment) -> dict[str, Any]:
46
+ payload: dict[str, Any] = {
47
+ "@odata.type": "#microsoft.graph.fileAttachment",
48
+ "name": attachment.filename,
49
+ "contentType": attachment.content_type,
50
+ "contentBytes": base64.b64encode(attachment.content).decode("ascii"),
51
+ }
52
+ if attachment.content_id:
53
+ payload["isInline"] = True
54
+ payload["contentId"] = attachment.content_id
55
+ return payload
56
+
57
+
58
+ class MicrosoftGraphAdapter(OutboxAdapterABC):
59
+ """Sends through Microsoft Graph as an Exchange Online mailbox, with the
60
+ client credentials of an Entra app registration.
61
+
62
+ The app needs the right to send as that mailbox: either the ``Mail.Send``
63
+ application permission, or (narrower) Exchange Online Application RBAC
64
+ scoped to the mailbox, in which case the token carries no ``Mail.Send``
65
+ role and Exchange does the check. Attachments above ~2.9 MB go through a
66
+ draft and upload sessions, which needs ``Mail.ReadWrite`` as well.
67
+
68
+ ``mailbox`` is the user whose mailbox sends; without it, the message's
69
+ sender is. A sender other than the mailbox goes in ``from``, which needs
70
+ Send As or Send on Behalf rights on that address."""
71
+
72
+ def __init__(
73
+ self,
74
+ tenant_id: str,
75
+ client_id: str,
76
+ client_secret: str,
77
+ mailbox: str | None = None,
78
+ save_to_sent_items: bool = True,
79
+ timeout: float = 30.0,
80
+ base_url: str = _GRAPH_URL,
81
+ login_url: str = _LOGIN_URL,
82
+ ) -> None:
83
+ super().__init__(driver_name="microsoft-graph")
84
+
85
+ self._tenant_id = tenant_id
86
+ self._client_id = client_id
87
+ self._client_secret = client_secret
88
+ self._mailbox = mailbox
89
+ self._save_to_sent_items = save_to_sent_items
90
+ self._timeout = timeout
91
+ self._base_url = base_url.rstrip("/")
92
+ self._login_url = login_url.rstrip("/")
93
+
94
+ def send_mail(self, message: Message) -> str:
95
+ """Returns the Message-ID header: Graph's sendMail answers without an id,
96
+ so the adapter sets the internet message id itself (or keeps the one in
97
+ ``message.headers``).
98
+
99
+ Graph only takes custom headers that start with ``X-``; others are left
100
+ out. ``idempotency_key``, ``tag``, ``metadata``, the tracking options
101
+ and ``require_tls`` have no Graph equivalent and are ignored."""
102
+ if not (self._tenant_id and self._client_id and self._client_secret):
103
+ raise AdapterError("sending through Microsoft Graph needs a tenant id, client id and client secret")
104
+
105
+ sender = require_sender(message)
106
+ mailbox = self._mailbox or sender.email
107
+ message_id = message.headers.get("Message-ID") or make_msgid(domain=mailbox.rpartition("@")[2] or None)
108
+ payload = self._payload(message, sender, mailbox, message_id)
109
+ user = f"/users/{urllib.parse.quote(mailbox, safe='')}"
110
+
111
+ if sum(len(attachment.content) for attachment in message.attachments) <= INLINE_ATTACHMENT_LIMIT_BYTES:
112
+ payload["attachments"] = [_attachment_payload(attachment) for attachment in message.attachments]
113
+ self._graph(f"{user}/sendMail", {"message": payload, "saveToSentItems": self._save_to_sent_items})
114
+ else:
115
+ self._send_with_uploaded_attachments(user, payload, message.attachments)
116
+
117
+ return message_id
118
+
119
+ def _payload(self, message: Message, sender: Address, mailbox: str, message_id: str) -> dict[str, Any]:
120
+ if message.html is not None:
121
+ body = {"contentType": "HTML", "content": message.html}
122
+ else:
123
+ body = {"contentType": "Text", "content": message.text or ""}
124
+
125
+ payload: dict[str, Any] = {
126
+ "subject": message.subject,
127
+ "body": body,
128
+ "toRecipients": _recipients(message.to),
129
+ "ccRecipients": _recipients(message.cc),
130
+ "bccRecipients": _recipients(message.bcc),
131
+ "replyTo": _recipients(message.reply_to),
132
+ "internetMessageId": message_id,
133
+ }
134
+
135
+ if sender.email.lower() != mailbox.lower():
136
+ payload["from"] = _recipients([sender])[0]
137
+
138
+ headers = [
139
+ {"name": name, "value": value} for name, value in message.headers.items() if name.lower().startswith("x-")
140
+ ]
141
+ if headers:
142
+ payload["internetMessageHeaders"] = headers
143
+
144
+ return payload
145
+
146
+ # -- large attachments ------------------------------------------------------
147
+
148
+ def _send_with_uploaded_attachments(
149
+ self, user: str, payload: dict[str, Any], attachments: list[Attachment]
150
+ ) -> None:
151
+ draft_id = self._graph(f"{user}/messages", payload).get("id")
152
+ if not isinstance(draft_id, str) or not draft_id:
153
+ raise AdapterError("Microsoft Graph created the draft without returning its id", transient=True)
154
+
155
+ draft = f"{user}/messages/{urllib.parse.quote(draft_id, safe='')}"
156
+ try:
157
+ for attachment in attachments:
158
+ if len(attachment.content) <= INLINE_ATTACHMENT_LIMIT_BYTES:
159
+ self._graph(f"{draft}/attachments", _attachment_payload(attachment))
160
+ else:
161
+ self._upload(draft, attachment)
162
+ except AdapterError:
163
+ self._discard_draft(draft)
164
+ raise
165
+
166
+ self._graph(f"{draft}/send")
167
+
168
+ def _upload(self, draft: str, attachment: Attachment) -> None:
169
+ size = len(attachment.content)
170
+ item: dict[str, Any] = {
171
+ "attachmentType": "file",
172
+ "name": attachment.filename,
173
+ "size": size,
174
+ "contentType": attachment.content_type,
175
+ "isInline": attachment.content_id is not None,
176
+ }
177
+ if attachment.content_id:
178
+ item["contentId"] = attachment.content_id
179
+
180
+ upload_url = self._graph(f"{draft}/attachments/createUploadSession", {"AttachmentItem": item}).get("uploadUrl")
181
+ if not isinstance(upload_url, str) or not upload_url:
182
+ raise AdapterError("Microsoft Graph returned no upload url for an attachment", transient=True)
183
+
184
+ # The upload url is pre-authenticated: sending the bearer token along is refused.
185
+ for offset in range(0, size, _UPLOAD_CHUNK_BYTES):
186
+ chunk = attachment.content[offset : offset + _UPLOAD_CHUNK_BYTES]
187
+ headers = {
188
+ "Content-Type": "application/octet-stream",
189
+ "Content-Range": f"bytes {offset}-{offset + len(chunk) - 1}/{size}",
190
+ }
191
+ self._request("PUT", upload_url, headers, chunk)
192
+
193
+ def _discard_draft(self, draft: str) -> None:
194
+ """Best effort: a draft left behind only clutters the mailbox."""
195
+ try:
196
+ self._graph(draft, method="DELETE")
197
+ except AdapterError:
198
+ pass
199
+
200
+ # -- auth -------------------------------------------------------------------
201
+
202
+ def _token_key(self) -> tuple[str, str, str]:
203
+ return self._tenant_id, self._client_id, hashlib.sha256(self._client_secret.encode("utf-8")).hexdigest()
204
+
205
+ def _access_token(self) -> tuple[str, bool]:
206
+ """The token, and whether it came from the cache."""
207
+ key = self._token_key()
208
+ with _tokens_lock:
209
+ cached = _tokens.get(key)
210
+ if cached is not None and cached[1] > time.monotonic():
211
+ return cached[0], True
212
+
213
+ url = f"{self._login_url}/{urllib.parse.quote(self._tenant_id, safe='')}/oauth2/v2.0/token"
214
+ form = urllib.parse.urlencode(
215
+ {
216
+ "client_id": self._client_id,
217
+ "client_secret": self._client_secret,
218
+ "scope": "https://graph.microsoft.com/.default",
219
+ "grant_type": "client_credentials",
220
+ }
221
+ ).encode("ascii")
222
+
223
+ try:
224
+ body = self._request("POST", url, {"Content-Type": "application/x-www-form-urlencoded"}, form)
225
+ except AdapterError as exc:
226
+ # The error body names the reason (AADSTS7000215: invalid secret, ...);
227
+ # its first line is enough and never contains the secret.
228
+ raise AdapterError(
229
+ f"could not get a Microsoft Graph token: {exc.args[0]}",
230
+ status_code=exc.status_code,
231
+ transient=exc.transient,
232
+ ) from exc
233
+
234
+ try:
235
+ decoded = json.loads(body)
236
+ token = decoded["access_token"]
237
+ expires_in = int(decoded.get("expires_in") or 3600)
238
+ except (ValueError, KeyError, TypeError) as exc:
239
+ raise AdapterError("Microsoft Graph's token response has no access token", transient=True) from exc
240
+
241
+ with _tokens_lock:
242
+ _tokens[key] = (token, time.monotonic() + max(60, expires_in - 300))
243
+ return str(token), False
244
+
245
+ def _forget_token(self) -> None:
246
+ with _tokens_lock:
247
+ _tokens.pop(self._token_key(), None)
248
+
249
+ # -- http -------------------------------------------------------------------
250
+
251
+ def _graph(self, path: str, payload: dict[str, Any] | None = None, method: str = "POST") -> dict[str, Any]:
252
+ data = json.dumps(payload).encode("utf-8") if payload is not None else None
253
+ headers = {"Accept": "application/json", **({"Content-Type": "application/json"} if data is not None else {})}
254
+
255
+ token, cached = self._access_token()
256
+ try:
257
+ body = self._request(method, self._base_url + path, {**headers, "Authorization": f"Bearer {token}"}, data)
258
+ except AdapterError as exc:
259
+ if exc.status_code != 401:
260
+ raise
261
+ self._forget_token()
262
+ if not cached:
263
+ raise
264
+ # A cached token Graph no longer takes (revoked, or the clock drifted):
265
+ # once more with a fresh one. A 401 means nothing was accepted.
266
+ token, _ = self._access_token()
267
+ body = self._request(method, self._base_url + path, {**headers, "Authorization": f"Bearer {token}"}, data)
268
+
269
+ if not body.strip():
270
+ return {}
271
+ try:
272
+ decoded = json.loads(body)
273
+ except ValueError as exc:
274
+ raise AdapterError(f"Microsoft Graph returned invalid JSON for {method} {path}", transient=True) from exc
275
+ return decoded if isinstance(decoded, dict) else {}
276
+
277
+ def _request(self, method: str, url: str, headers: dict[str, str], data: bytes | None = None) -> bytes:
278
+ request = urllib.request.Request(url, data=data, method=method, headers={**headers, "User-Agent": "flowbox"})
279
+
280
+ try:
281
+ with urllib.request.urlopen(request, timeout=self._timeout) as response:
282
+ body: bytes = response.read()
283
+ return body
284
+ except urllib.error.HTTPError as exc:
285
+ raise AdapterError(
286
+ f"Microsoft Graph {method} {urllib.parse.urlsplit(url).path} failed with HTTP {exc.code}: "
287
+ f"{self._reason(exc.read())}",
288
+ status_code=exc.code,
289
+ transient=_transient(exc.code),
290
+ ) from exc
291
+ except (urllib.error.URLError, OSError) as exc:
292
+ raise AdapterError(f"could not reach Microsoft Graph: {exc}", transient=True) from exc
293
+
294
+ @staticmethod
295
+ def _reason(body: bytes) -> str:
296
+ """Graph's ``error.code: error.message``, or the token endpoint's
297
+ ``error_description`` up to its first line break (the rest is trace ids)."""
298
+ try:
299
+ decoded = json.loads(body)
300
+ except ValueError:
301
+ return body.decode("utf-8", errors="replace")[:500]
302
+
303
+ if isinstance(decoded, dict):
304
+ error = decoded.get("error")
305
+ if isinstance(error, dict):
306
+ return f"{error.get('code')}: {error.get('message')}"
307
+ description = decoded.get("error_description")
308
+ if isinstance(description, str):
309
+ return description.splitlines()[0] if description else str(error)
310
+ return body.decode("utf-8", errors="replace")[:500]
@@ -14,6 +14,7 @@ from flowbox.adapters import (
14
14
  InboxAdapterABC,
15
15
  LettermintAdapter,
16
16
  LogAdapter,
17
+ MicrosoftGraphAdapter,
17
18
  OutboxAdapterABC,
18
19
  SMTPAdapter,
19
20
  )
@@ -23,6 +24,7 @@ class OutboxDriver(StrEnum):
23
24
  LOG = "log"
24
25
  SMTP = "smtp"
25
26
  LETTERMINT = "lettermint"
27
+ GRAPH = "graph"
26
28
 
27
29
 
28
30
  class InboxDriver(StrEnum):
@@ -95,6 +97,15 @@ class FlowboxSettings(BaseSettings):
95
97
  #: The inbound route webhook's signing secret (``whsec_...``): lettermint_webhooks().
96
98
  lettermint_webhook_secret: str | None = None
97
99
 
100
+ #: MAIL_OUTBOX=graph: an Entra app registration's client credentials.
101
+ graph_tenant_id: str | None = None
102
+ graph_client_id: str | None = None
103
+ graph_client_secret: str | None = None
104
+ #: The mailbox that sends; MAIL_FROM_ADDRESS (or each message's sender) otherwise.
105
+ graph_sender: str | None = None
106
+ #: Keep a copy of each sent mail in the mailbox's Sent Items.
107
+ graph_save_to_sent_items: bool = True
108
+
98
109
  @field_validator("mail_outbox", "mail_inbox", mode="before")
99
110
  @classmethod
100
111
  def _normalize_driver(cls, value: Any) -> Any:
@@ -117,6 +128,10 @@ class FlowboxSettings(BaseSettings):
117
128
  "lettermint_team_token",
118
129
  "lettermint_project_id",
119
130
  "lettermint_webhook_secret",
131
+ "graph_tenant_id",
132
+ "graph_client_id",
133
+ "graph_client_secret",
134
+ "graph_sender",
120
135
  mode="before",
121
136
  )
122
137
  @classmethod
@@ -136,6 +151,12 @@ class FlowboxSettings(BaseSettings):
136
151
  required.append(("SMTP_HOST", self.smtp_host))
137
152
  if self.mail_outbox is OutboxDriver.LETTERMINT:
138
153
  required.append(("LETTERMINT_PROJECT_TOKEN", self.lettermint_project_token))
154
+ if self.mail_outbox is OutboxDriver.GRAPH:
155
+ required += [
156
+ ("GRAPH_TENANT_ID", self.graph_tenant_id),
157
+ ("GRAPH_CLIENT_ID", self.graph_client_id),
158
+ ("GRAPH_CLIENT_SECRET", self.graph_client_secret),
159
+ ]
139
160
  if self.mail_inbox is InboxDriver.IMAP:
140
161
  required += [
141
162
  ("IMAP_HOST", self.imap_host),
@@ -176,6 +197,16 @@ class FlowboxSettings(BaseSettings):
176
197
  route=self.lettermint_route,
177
198
  timeout=self.mail_timeout,
178
199
  )
200
+ case OutboxDriver.GRAPH:
201
+ assert self.graph_tenant_id and self.graph_client_id and self.graph_client_secret
202
+ return MicrosoftGraphAdapter(
203
+ self.graph_tenant_id,
204
+ self.graph_client_id,
205
+ self.graph_client_secret,
206
+ mailbox=self.graph_sender or self.mail_from_address,
207
+ save_to_sent_items=self.graph_save_to_sent_items,
208
+ timeout=self.mail_timeout,
209
+ )
179
210
 
180
211
  def inbox_adapter(self) -> InboxAdapterABC:
181
212
  match self.mail_inbox:
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flowbox
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: A vendor-neutral email connector: read inboxes and send mail through the adapter you choose.
5
5
  Author: Flowmatic, UniForceMusic
6
6
  License-Expression: MIT
7
7
  Project-URL: Homepage, https://github.com/Flowmatic-AI/flowmatic-toolkit
8
8
  Project-URL: Repository, https://github.com/Flowmatic-AI/flowmatic-toolkit
9
9
  Project-URL: Issues, https://github.com/Flowmatic-AI/flowmatic-toolkit/issues
10
- Keywords: email,mail,inbox,outbox,smtp,imap,lettermint
10
+ Keywords: email,mail,inbox,outbox,smtp,imap,lettermint,microsoft-graph,exchange
11
11
  Classifier: Development Status :: 2 - Pre-Alpha
12
12
  Classifier: Intended Audience :: Developers
13
13
  Classifier: Programming Language :: Python :: 3
@@ -34,12 +34,13 @@ A vendor-neutral email connector: read inboxes and send mail through the adapter
34
34
 
35
35
  [`../project`](../project) is a small flowlab app that shows how to wire it into an application: settings, one factory module, a queued send job, polling and a webhook route.
36
36
 
37
- | Adapter | Inbox | Webhooks | Outbox |
38
- |---------------------|:-----:|:--------:|:------:|
39
- | `IMAPAdapter` | ✓ | | |
40
- | `SMTPAdapter` | | | ✓ |
41
- | `LettermintAdapter` | ✓ | ✓ | ✓ |
42
- | `LogAdapter` | | | ✓ |
37
+ | Adapter | Inbox | Webhooks | Outbox |
38
+ |-------------------------|:-----:|:--------:|:------:|
39
+ | `IMAPAdapter` | ✓ | | |
40
+ | `SMTPAdapter` | | | ✓ |
41
+ | `LettermintAdapter` | ✓ | ✓ | ✓ |
42
+ | `MicrosoftGraphAdapter` | | | ✓ |
43
+ | `LogAdapter` | | | ✓ |
43
44
 
44
45
  `LogAdapter` sends nothing; it logs each message on the `flowbox.log` logger, like Laravel's log mailer. Use it for local work, not production.
45
46
 
@@ -72,7 +73,7 @@ Each `outbox()` / `inbox()` call builds a new flow: open one per job, command or
72
73
 
73
74
  | Variable | Default | Used for |
74
75
  |---|---|---|
75
- | `MAIL_OUTBOX` | `log` | `log`, `smtp` or `lettermint` |
76
+ | `MAIL_OUTBOX` | `log` | `log`, `smtp`, `lettermint` or `graph` |
76
77
  | `MAIL_INBOX` | unset | `imap` or `lettermint`; unset when the app reads no mail |
77
78
  | `MAIL_FROM_ADDRESS`, `MAIL_FROM_NAME` | unset | The sender of messages that set none |
78
79
  | `MAIL_TIMEOUT` | `30` | Seconds before a provider call gives up |
@@ -83,6 +84,9 @@ Each `outbox()` / `inbox()` call builds a new flow: open one per job, command or
83
84
  | `LETTERMINT_PROJECT_TOKEN`, `LETTERMINT_ROUTE` | | `MAIL_OUTBOX=lettermint` |
84
85
  | `LETTERMINT_TEAM_TOKEN`, `LETTERMINT_PROJECT_ID` | | `MAIL_INBOX=lettermint` |
85
86
  | `LETTERMINT_WEBHOOK_SECRET` | | `settings.lettermint_webhooks()` |
87
+ | `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET` | | `MAIL_OUTBOX=graph` |
88
+ | `GRAPH_SENDER` | `MAIL_FROM_ADDRESS` | The mailbox Graph sends as |
89
+ | `GRAPH_SAVE_TO_SENT_ITEMS` | `true` | Keep a copy in the mailbox's Sent Items |
86
90
 
87
91
  Webhooks stay per vendor: `settings.lettermint_webhooks()` returns a `FlowInbox[LettermintAdapter]` for that vendor's webhook route. Your own adapter goes in by overriding `outbox_adapter()` or `inbox_adapter()`:
88
92
 
@@ -118,12 +122,12 @@ with FlowOutbox.connect_smtp("smtp.example.com", "user", "secret", sender=Addres
118
122
 
119
123
  A few `Message` fields are for providers that support them; an adapter whose provider has no equivalent ignores them.
120
124
 
121
- | Field | Lettermint | SMTP |
125
+ | Field | Lettermint | SMTP, Microsoft Graph |
122
126
  |---|---|---|
123
127
  | `idempotency_key` | `Idempotency-Key`: the same key is sent once, so retrying after an uncertain failure cannot send twice | ignored |
124
128
  | `tag`, `metadata` | stored with the message, returned in delivery webhooks | ignored |
125
129
  | `track_opens`, `track_clicks` | per-message tracking; `None` keeps the project default | ignored |
126
- | `require_tls` | `tls: enforced` | ignored; the connection's own `encryption` applies |
130
+ | `require_tls` | `tls: enforced` | ignored; SMTP's own `encryption` applies |
127
131
 
128
132
  ### Errors
129
133
 
@@ -195,3 +199,28 @@ lettermint = LettermintAdapter(project_token="lm_...", team_token="lm_team_...",
195
199
  inbox = FlowInbox(lettermint)
196
200
  outbox = FlowOutbox(lettermint, sender=Address("noreply@acme.com"))
197
201
  ```
202
+
203
+ ## Microsoft Graph
204
+
205
+ Sends as an Exchange Online mailbox (`fleet@acme.com`, say) with the client credentials of an Entra app registration, instead of SMTP:
206
+
207
+ ```python
208
+ from flowbox import Address, FlowOutbox
209
+
210
+ outbox = FlowOutbox.connect_microsoft_graph(
211
+ tenant_id="...",
212
+ client_id="...",
213
+ client_secret="...",
214
+ mailbox="fleet@acme.com",
215
+ sender=Address("fleet@acme.com", "Fleet"),
216
+ )
217
+ ```
218
+
219
+ The app needs the right to send as that mailbox. Either grant the `Mail.Send` application permission (every mailbox in the tenant), or have the tenant's admin scope it to the one mailbox with **Exchange Online Application RBAC** ("Application Mail.Send"). With RBAC the token carries no `Mail.Send` role; that is expected, Exchange does the check.
220
+
221
+ - Without `mailbox`, each message's sender is the mailbox. A sender other than the mailbox goes in `from`, which needs Send As or Send on Behalf rights on that address.
222
+ - Attachments up to ~2.9 MB together go inline with `sendMail` (Graph caps a request at 4 MB). Larger ones go through a draft and upload sessions, which also needs `Mail.ReadWrite` ("Application Mail.ReadWrite"); if an upload fails, the draft is deleted.
223
+ - `sendMail` returns no id, so `send_mail()` sets the internet message id itself and returns it, like SMTP's `Message-ID`; a `Message-ID` in `message.headers` is kept.
224
+ - Graph only accepts custom headers that start with `X-`; other headers are left out.
225
+ - Tokens are cached in the process until five minutes before they expire, shared by every adapter with the same credentials. A cached token Graph refuses is replaced once.
226
+ - A failed token request raises an `AdapterError` with Entra's reason (`AADSTS7000215: Invalid client secret provided.`), never the secret.
@@ -17,6 +17,7 @@ src/flowbox/adapters/_abc.py
17
17
  src/flowbox/adapters/_imap.py
18
18
  src/flowbox/adapters/_lettermint.py
19
19
  src/flowbox/adapters/_log.py
20
+ src/flowbox/adapters/_microsoft_graph.py
20
21
  src/flowbox/adapters/_smtp.py
21
22
  src/flowbox/settings/__init__.py
22
23
  src/flowbox/settings/_settings.py
@@ -24,6 +25,7 @@ tests/test_boundary.py
24
25
  tests/test_flowbox.py
25
26
  tests/test_imap.py
26
27
  tests/test_lettermint.py
28
+ tests/test_microsoft_graph.py
27
29
  tests/test_mime.py
28
30
  tests/test_settings.py
29
31
  tests/test_smtp.py
@@ -0,0 +1,269 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import io
5
+ import json
6
+ import urllib.error
7
+ import urllib.parse
8
+ from collections.abc import Iterator
9
+ from typing import Any
10
+
11
+ import pytest
12
+
13
+ from flowbox import AdapterError, Address, Attachment, FlowOutbox, Message
14
+ from flowbox.adapters import MicrosoftGraphAdapter
15
+ from flowbox.adapters import _microsoft_graph as graph
16
+
17
+ TOKEN_URL = "https://login.microsoftonline.com/tenant-1/oauth2/v2.0/token"
18
+ USER_URL = "https://graph.microsoft.com/v1.0/users/wagenpark%40heydayfm.nl"
19
+ SEND_URL = f"{USER_URL}/sendMail"
20
+ UPLOAD_URL = "https://outlook.office.com/upload/abc?authtoken=x"
21
+
22
+
23
+ class FakeGraph:
24
+ """Answers urlopen like login.microsoftonline.com and Graph would; ``fail``
25
+ maps a url to the HTTP status (and JSON body) it answers with instead."""
26
+
27
+ def __init__(self) -> None:
28
+ self.requests: list[tuple[str, str, dict[str, str], bytes | None]] = []
29
+ self.fail: dict[str, list[tuple[int, dict[str, Any]]]] = {}
30
+ self.tokens = 0
31
+
32
+ def __call__(self, request: Any, timeout: float) -> Any:
33
+ headers = {name.lower(): value for name, value in request.header_items()}
34
+ self.requests.append((request.get_method(), request.full_url, headers, request.data))
35
+
36
+ failures = self.fail.get(request.full_url)
37
+ if failures:
38
+ code, body = failures.pop(0)
39
+ raise urllib.error.HTTPError(
40
+ request.full_url, code, "no", {}, io.BytesIO(json.dumps(body).encode()) # type: ignore[arg-type]
41
+ )
42
+
43
+ if request.full_url == TOKEN_URL:
44
+ self.tokens += 1
45
+ return io.BytesIO(json.dumps({"access_token": f"token-{self.tokens}", "expires_in": 3599}).encode())
46
+ if request.full_url == f"{USER_URL}/messages":
47
+ return io.BytesIO(json.dumps({"id": "draft-1"}).encode())
48
+ if request.full_url.endswith("/createUploadSession"):
49
+ return io.BytesIO(json.dumps({"uploadUrl": UPLOAD_URL}).encode())
50
+ return io.BytesIO(b"")
51
+
52
+ def to(self, url: str) -> list[tuple[str, str, dict[str, str], bytes | None]]:
53
+ return [request for request in self.requests if request[1] == url]
54
+
55
+ def json(self, url: str, index: int = 0) -> Any:
56
+ data = self.to(url)[index][3]
57
+ assert data is not None
58
+ return json.loads(data)
59
+
60
+
61
+ @pytest.fixture(autouse=True)
62
+ def no_cached_tokens() -> Iterator[None]:
63
+ graph._tokens.clear()
64
+ yield
65
+ graph._tokens.clear()
66
+
67
+
68
+ @pytest.fixture
69
+ def api(monkeypatch: pytest.MonkeyPatch) -> FakeGraph:
70
+ fake = FakeGraph()
71
+ monkeypatch.setattr("urllib.request.urlopen", fake)
72
+ return fake
73
+
74
+
75
+ def _outbox(mailbox: str | None = "wagenpark@heydayfm.nl", secret: str = "secret-1") -> FlowOutbox:
76
+ return FlowOutbox.connect_microsoft_graph(
77
+ "tenant-1", "client-1", secret, mailbox=mailbox, sender=Address("wagenpark@heydayfm.nl", "Wagenpark")
78
+ )
79
+
80
+
81
+ def _message(**fields: Any) -> Message:
82
+ return Message(**{"subject": "APK verlengen", "to": [Address("jan@example.com", "Jan Jansen")], **fields})
83
+
84
+
85
+ def test_it_sends_through_graph_as_the_mailbox(api: FakeGraph) -> None:
86
+ message_id = _outbox().send_mail(
87
+ _message(
88
+ cc=[Address("hr@example.com")],
89
+ bcc=[Address("archief@example.com")],
90
+ reply_to=[Address("fleet@heydayfm.nl")],
91
+ html="<p>Hallo</p>",
92
+ headers={"X-Email-Log-Id": "42", "List-Unsubscribe": "<mailto:x@example.com>"},
93
+ attachments=[Attachment("polis.pdf", b"pdf-bytes"), Attachment("logo.png", b"png", content_id="logo")],
94
+ )
95
+ )
96
+
97
+ token_form = dict(urllib.parse.parse_qsl((api.to(TOKEN_URL)[0][3] or b"").decode()))
98
+ assert token_form == {
99
+ "client_id": "client-1",
100
+ "client_secret": "secret-1",
101
+ "scope": "https://graph.microsoft.com/.default",
102
+ "grant_type": "client_credentials",
103
+ }
104
+
105
+ _, _, headers, _ = api.to(SEND_URL)[0]
106
+ assert headers["authorization"] == "Bearer token-1"
107
+
108
+ sent = api.json(SEND_URL)
109
+ payload = sent["message"]
110
+ assert sent["saveToSentItems"] is True
111
+ assert payload["subject"] == "APK verlengen"
112
+ assert payload["body"] == {"contentType": "HTML", "content": "<p>Hallo</p>"}
113
+ assert payload["toRecipients"] == [{"emailAddress": {"address": "jan@example.com", "name": "Jan Jansen"}}]
114
+ assert payload["ccRecipients"] == [{"emailAddress": {"address": "hr@example.com"}}]
115
+ assert payload["bccRecipients"] == [{"emailAddress": {"address": "archief@example.com"}}]
116
+ assert payload["replyTo"] == [{"emailAddress": {"address": "fleet@heydayfm.nl"}}]
117
+ assert payload["internetMessageHeaders"] == [{"name": "X-Email-Log-Id", "value": "42"}]
118
+ assert payload["internetMessageId"] == message_id
119
+ assert message_id.endswith("@heydayfm.nl>")
120
+ assert "from" not in payload
121
+
122
+ pdf, logo = payload["attachments"]
123
+ assert (pdf["name"], pdf["contentType"], base64.b64decode(pdf["contentBytes"])) == (
124
+ "polis.pdf",
125
+ "application/pdf",
126
+ b"pdf-bytes",
127
+ )
128
+ assert "isInline" not in pdf
129
+ assert (logo["isInline"], logo["contentId"]) == (True, "logo")
130
+
131
+
132
+ def test_a_text_body_and_a_message_id_of_its_own(api: FakeGraph) -> None:
133
+ message_id = _outbox().send_mail(_message(text="Hallo", headers={"Message-ID": "<own@heydayfm.nl>"}))
134
+
135
+ payload = api.json(SEND_URL)["message"]
136
+ assert payload["body"] == {"contentType": "Text", "content": "Hallo"}
137
+ assert payload["internetMessageId"] == message_id == "<own@heydayfm.nl>"
138
+ assert "internetMessageHeaders" not in payload
139
+
140
+
141
+ def test_without_a_mailbox_the_sender_sends(api: FakeGraph) -> None:
142
+ _outbox(mailbox=None).send_mail(_message(text="Hallo"))
143
+
144
+ assert len(api.to(SEND_URL)) == 1
145
+
146
+
147
+ def test_another_sender_than_the_mailbox_goes_in_from(api: FakeGraph) -> None:
148
+ _outbox().send_mail(_message(text="Hallo", sender=Address("info@heydayfm.nl", "Heyday")))
149
+
150
+ payload = api.json(SEND_URL)["message"]
151
+ assert payload["from"] == {"emailAddress": {"address": "info@heydayfm.nl", "name": "Heyday"}}
152
+
153
+
154
+ def test_the_token_is_shared_between_adapters(api: FakeGraph) -> None:
155
+ _outbox().send_mail(_message(text="Eén"))
156
+ _outbox().send_mail(_message(text="Twee"))
157
+
158
+ assert len(api.to(TOKEN_URL)) == 1
159
+ assert len(api.to(SEND_URL)) == 2
160
+
161
+ _outbox(secret="secret-2").send_mail(_message(text="Drie"))
162
+ assert len(api.to(TOKEN_URL)) == 2
163
+
164
+
165
+ def test_a_refused_cached_token_is_replaced_once(api: FakeGraph) -> None:
166
+ _outbox().send_mail(_message(text="Eén"))
167
+ api.fail[SEND_URL] = [(401, {"error": {"code": "InvalidAuthenticationToken", "message": "expired"}})]
168
+
169
+ _outbox().send_mail(_message(text="Twee"))
170
+
171
+ assert len(api.to(TOKEN_URL)) == 2
172
+ assert api.to(SEND_URL)[-1][2]["authorization"] == "Bearer token-2"
173
+
174
+
175
+ def test_a_fresh_token_refused_is_not_retried(api: FakeGraph) -> None:
176
+ api.fail[SEND_URL] = [(401, {"error": {"code": "InvalidAuthenticationToken", "message": "no"}})] * 2
177
+
178
+ with pytest.raises(AdapterError) as raised:
179
+ _outbox().send_mail(_message(text="Hallo"))
180
+
181
+ assert raised.value.status_code == 401
182
+ assert len(api.to(SEND_URL)) == 1
183
+ assert graph._tokens == {}
184
+
185
+
186
+ @pytest.mark.parametrize(("code", "transient"), [(400, False), (403, False), (429, True), (503, True)])
187
+ def test_a_graph_refusal_carries_graphs_reason(api: FakeGraph, code: int, transient: bool) -> None:
188
+ api.fail[SEND_URL] = [(code, {"error": {"code": "ErrorAccessDenied", "message": "Access is denied."}})]
189
+
190
+ with pytest.raises(AdapterError, match=r"ErrorAccessDenied: Access is denied\.") as raised:
191
+ _outbox().send_mail(_message(text="Hallo"))
192
+
193
+ assert (raised.value.status_code, raised.value.transient) == (code, transient)
194
+
195
+
196
+ def test_a_failed_token_request_never_echoes_the_secret(api: FakeGraph) -> None:
197
+ description = "AADSTS7000215: Invalid client secret provided.\r\nTrace ID: x"
198
+ api.fail[TOKEN_URL] = [(401, {"error": "invalid_client", "error_description": description})]
199
+
200
+ with pytest.raises(AdapterError) as raised:
201
+ _outbox().send_mail(_message(text="Hallo"))
202
+
203
+ assert "AADSTS7000215" in str(raised.value)
204
+ assert "secret-1" not in str(raised.value)
205
+ assert "Trace ID" not in str(raised.value)
206
+ assert (raised.value.status_code, raised.value.transient) == (401, False)
207
+ assert api.to(SEND_URL) == []
208
+
209
+
210
+ def test_large_attachments_go_through_a_draft_and_an_upload_session(
211
+ api: FakeGraph, monkeypatch: pytest.MonkeyPatch
212
+ ) -> None:
213
+ monkeypatch.setattr(graph, "INLINE_ATTACHMENT_LIMIT_BYTES", 10)
214
+ monkeypatch.setattr(graph, "_UPLOAD_CHUNK_BYTES", 8)
215
+ large = b"a" * 20
216
+
217
+ _outbox().send_mail(
218
+ _message(text="Zie bijlage", attachments=[Attachment("klein.txt", b"small"), Attachment("groot.pdf", large)])
219
+ )
220
+
221
+ draft = f"{USER_URL}/messages/draft-1"
222
+ assert api.to(SEND_URL) == []
223
+ assert "attachments" not in api.json(f"{USER_URL}/messages")
224
+ assert api.json(f"{draft}/attachments")["name"] == "klein.txt"
225
+ assert api.json(f"{draft}/attachments/createUploadSession")["AttachmentItem"] == {
226
+ "attachmentType": "file",
227
+ "name": "groot.pdf",
228
+ "size": 20,
229
+ "contentType": "application/pdf",
230
+ "isInline": False,
231
+ }
232
+
233
+ chunks = api.to(UPLOAD_URL)
234
+ assert [request[2]["content-range"] for request in chunks] == ["bytes 0-7/20", "bytes 8-15/20", "bytes 16-19/20"]
235
+ assert b"".join(request[3] or b"" for request in chunks) == large
236
+ assert all("authorization" not in request[2] for request in chunks)
237
+ assert [request[0] for request in api.to(f"{draft}/send")] == ["POST"]
238
+
239
+
240
+ def test_a_failed_upload_discards_the_draft(api: FakeGraph, monkeypatch: pytest.MonkeyPatch) -> None:
241
+ monkeypatch.setattr(graph, "INLINE_ATTACHMENT_LIMIT_BYTES", 10)
242
+ api.fail[UPLOAD_URL] = [(503, {})]
243
+
244
+ with pytest.raises(AdapterError) as raised:
245
+ _outbox().send_mail(_message(text="Zie bijlage", attachments=[Attachment("groot.pdf", b"a" * 20)]))
246
+
247
+ draft = f"{USER_URL}/messages/draft-1"
248
+ assert raised.value.transient
249
+ assert [request[0] for request in api.to(draft)] == ["DELETE"]
250
+ assert api.to(f"{draft}/send") == []
251
+
252
+
253
+ def test_it_refuses_to_send_without_credentials(api: FakeGraph) -> None:
254
+ adapter = MicrosoftGraphAdapter("tenant-1", "client-1", "")
255
+
256
+ with pytest.raises(AdapterError, match="client secret"):
257
+ FlowOutbox(adapter, Address("wagenpark@heydayfm.nl")).send_mail(_message(text="Hallo"))
258
+ assert api.requests == []
259
+
260
+
261
+ def test_an_unreachable_graph_is_transient(monkeypatch: pytest.MonkeyPatch) -> None:
262
+ def fail(request: Any, timeout: float) -> Any:
263
+ raise urllib.error.URLError("timed out")
264
+
265
+ monkeypatch.setattr("urllib.request.urlopen", fail)
266
+
267
+ with pytest.raises(AdapterError) as raised:
268
+ _outbox().send_mail(_message(text="Hallo"))
269
+ assert (raised.value.status_code, raised.value.transient) == (None, True)
@@ -6,7 +6,14 @@ import pytest
6
6
  from pydantic import ValidationError
7
7
 
8
8
  from flowbox import Address, FlowOutbox, Message
9
- from flowbox.adapters import IMAPAdapter, LettermintAdapter, LogAdapter, OutboxAdapterABC, SMTPAdapter
9
+ from flowbox.adapters import (
10
+ IMAPAdapter,
11
+ LettermintAdapter,
12
+ LogAdapter,
13
+ MicrosoftGraphAdapter,
14
+ OutboxAdapterABC,
15
+ SMTPAdapter,
16
+ )
10
17
  from flowbox.settings import FlowboxSettings, InboxDriver, OutboxDriver
11
18
 
12
19
  ENV_NAMES = (
@@ -22,6 +29,11 @@ ENV_NAMES = (
22
29
  "LETTERMINT_PROJECT_TOKEN",
23
30
  "LETTERMINT_TEAM_TOKEN",
24
31
  "LETTERMINT_WEBHOOK_SECRET",
32
+ "GRAPH_TENANT_ID",
33
+ "GRAPH_CLIENT_ID",
34
+ "GRAPH_CLIENT_SECRET",
35
+ "GRAPH_SENDER",
36
+ "GRAPH_SAVE_TO_SENT_ITEMS",
25
37
  )
26
38
 
27
39
 
@@ -81,6 +93,26 @@ def test_lettermint_serves_each_side_with_its_own_credential() -> None:
81
93
  assert isinstance(settings.lettermint_webhooks().adapter, LettermintAdapter)
82
94
 
83
95
 
96
+ @pytest.mark.parametrize(
97
+ ("env", "mailbox"),
98
+ [({}, "noreply@acme.com"), ({"GRAPH_SENDER": "fleet@acme.com"}, "fleet@acme.com")],
99
+ )
100
+ def test_graph_sends_as_the_graph_sender_or_the_from_address(env: dict[str, str], mailbox: str) -> None:
101
+ settings = _settings(
102
+ MAIL_OUTBOX="graph",
103
+ MAIL_FROM_ADDRESS="noreply@acme.com",
104
+ GRAPH_TENANT_ID="tenant",
105
+ GRAPH_CLIENT_ID="client",
106
+ GRAPH_CLIENT_SECRET="secret",
107
+ GRAPH_SAVE_TO_SENT_ITEMS="false",
108
+ **env,
109
+ )
110
+
111
+ adapter = settings.outbox().adapter
112
+ assert isinstance(adapter, MicrosoftGraphAdapter)
113
+ assert (adapter._mailbox, adapter._save_to_sent_items) == (mailbox, False)
114
+
115
+
84
116
  def test_webhooks_need_their_secret() -> None:
85
117
  with pytest.raises(ValueError, match="LETTERMINT_WEBHOOK_SECRET"):
86
118
  _settings().lettermint_webhooks()
@@ -91,6 +123,7 @@ def test_webhooks_need_their_secret() -> None:
91
123
  [
92
124
  ({"MAIL_OUTBOX": "smtp"}, "SMTP_HOST"),
93
125
  ({"MAIL_OUTBOX": "lettermint"}, "LETTERMINT_PROJECT_TOKEN"),
126
+ ({"MAIL_OUTBOX": "graph", "GRAPH_TENANT_ID": "t"}, "GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET"),
94
127
  ({"MAIL_INBOX": "imap", "IMAP_HOST": "imap.acme.com"}, "IMAP_USERNAME, IMAP_PASSWORD"),
95
128
  ({"MAIL_INBOX": "lettermint"}, "LETTERMINT_TEAM_TOKEN"),
96
129
  ],
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes