flowbox 0.1.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.
- {flowbox-0.1.0/src/flowbox.egg-info → flowbox-0.3.0}/PKG-INFO +66 -9
- {flowbox-0.1.0 → flowbox-0.3.0}/README.md +64 -7
- {flowbox-0.1.0 → flowbox-0.3.0}/pyproject.toml +3 -3
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox/__init__.py +2 -1
- flowbox-0.3.0/src/flowbox/_exceptions.py +33 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox/_flowbox.py +27 -2
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox/_message.py +20 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox/adapters/__init__.py +2 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox/adapters/_lettermint.py +83 -15
- flowbox-0.3.0/src/flowbox/adapters/_microsoft_graph.py +310 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox/adapters/_smtp.py +13 -2
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox/settings/_settings.py +31 -0
- {flowbox-0.1.0 → flowbox-0.3.0/src/flowbox.egg-info}/PKG-INFO +66 -9
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox.egg-info/SOURCES.txt +2 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/tests/test_lettermint.py +122 -2
- flowbox-0.3.0/tests/test_microsoft_graph.py +269 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/tests/test_settings.py +34 -1
- {flowbox-0.1.0 → flowbox-0.3.0}/tests/test_smtp.py +26 -0
- flowbox-0.1.0/src/flowbox/_exceptions.py +0 -13
- {flowbox-0.1.0 → flowbox-0.3.0}/LICENSE +0 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/setup.cfg +0 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox/_mime.py +0 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox/adapters/_abc.py +0 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox/adapters/_imap.py +0 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox/adapters/_log.py +0 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox/py.typed +0 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox/settings/__init__.py +0 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox.egg-info/dependency_links.txt +0 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox.egg-info/requires.txt +0 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/src/flowbox.egg-info/top_level.txt +0 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/tests/test_boundary.py +0 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/tests/test_flowbox.py +0 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/tests/test_imap.py +0 -0
- {flowbox-0.1.0 → flowbox-0.3.0}/tests/test_mime.py +0 -0
- {flowbox-0.1.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.
|
|
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
|
|
38
|
-
|
|
39
|
-
| `IMAPAdapter`
|
|
40
|
-
| `SMTPAdapter`
|
|
41
|
-
| `LettermintAdapter`
|
|
42
|
-
| `
|
|
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 `
|
|
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
|
|
|
@@ -114,6 +118,30 @@ with FlowOutbox.connect_smtp("smtp.example.com", "user", "secret", sender=Addres
|
|
|
114
118
|
)
|
|
115
119
|
```
|
|
116
120
|
|
|
121
|
+
### Sending options
|
|
122
|
+
|
|
123
|
+
A few `Message` fields are for providers that support them; an adapter whose provider has no equivalent ignores them.
|
|
124
|
+
|
|
125
|
+
| Field | Lettermint | SMTP, Microsoft Graph |
|
|
126
|
+
|---|---|---|
|
|
127
|
+
| `idempotency_key` | `Idempotency-Key`: the same key is sent once, so retrying after an uncertain failure cannot send twice | ignored |
|
|
128
|
+
| `tag`, `metadata` | stored with the message, returned in delivery webhooks | ignored |
|
|
129
|
+
| `track_opens`, `track_clicks` | per-message tracking; `None` keeps the project default | ignored |
|
|
130
|
+
| `require_tls` | `tls: enforced` | ignored; SMTP's own `encryption` applies |
|
|
131
|
+
|
|
132
|
+
### Errors
|
|
133
|
+
|
|
134
|
+
Every provider failure is an `AdapterError`. `status_code` is the provider's HTTP status when it answered with one, and `transient` says whether trying again later may succeed (timeouts, dropped connections, rate limits, server errors, SMTP 4xx replies). A transient failure while sending can mean the message went out before the connection broke: retry with the same `idempotency_key`.
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
try:
|
|
138
|
+
outbox.send_mail(message)
|
|
139
|
+
except AdapterError as exc:
|
|
140
|
+
if not exc.transient:
|
|
141
|
+
raise
|
|
142
|
+
... # retry later, same message, same idempotency_key
|
|
143
|
+
```
|
|
144
|
+
|
|
117
145
|
## Reading
|
|
118
146
|
|
|
119
147
|
```python
|
|
@@ -154,6 +182,10 @@ async def inbound(request: Request) -> None:
|
|
|
154
182
|
|
|
155
183
|
Responding is up to your app. Providers retry deliveries that get no 2xx, so the same message can arrive twice; `message.id` stays the same.
|
|
156
184
|
|
|
185
|
+
A correctly signed webhook for another event (a delivery report sent to the same URL) raises `UnsupportedWebhookError`, a subclass of `AdapterError` with the event name in `event`; answer it with a 2xx so the provider stops retrying. Fields the provider sends that `Message` has no place for — Lettermint's `route`, envelope `recipient`, `is_spam`, `authentication_results` and the event `id` — are in `message.provider_data`, as sent, without the body and attachment contents.
|
|
186
|
+
|
|
187
|
+
A Lettermint route can deliver large attachments as signed download links instead of inline. `parse_webhook()` downloads them by default; `FlowInbox.connect_lettermint(webhook_secret=..., download_attachments=False)` leaves their `content` empty and their `url` in `provider_data`, so a queued job can fetch them after the webhook has been answered.
|
|
188
|
+
|
|
157
189
|
## Lettermint
|
|
158
190
|
|
|
159
191
|
One adapter covers everything; each part needs only its own credential. Sending uses a project token (`lm_...`), `retrieve_mails()` a team token (`lm_team_...`) with the team's inbound routes as the mailboxes, and `parse_webhook()` the inbound route webhook's signing secret (`whsec_...`).
|
|
@@ -167,3 +199,28 @@ lettermint = LettermintAdapter(project_token="lm_...", team_token="lm_team_...",
|
|
|
167
199
|
inbox = FlowInbox(lettermint)
|
|
168
200
|
outbox = FlowOutbox(lettermint, sender=Address("noreply@acme.com"))
|
|
169
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
|
|
8
|
-
|
|
9
|
-
| `IMAPAdapter`
|
|
10
|
-
| `SMTPAdapter`
|
|
11
|
-
| `LettermintAdapter`
|
|
12
|
-
| `
|
|
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 `
|
|
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
|
|
|
@@ -84,6 +88,30 @@ with FlowOutbox.connect_smtp("smtp.example.com", "user", "secret", sender=Addres
|
|
|
84
88
|
)
|
|
85
89
|
```
|
|
86
90
|
|
|
91
|
+
### Sending options
|
|
92
|
+
|
|
93
|
+
A few `Message` fields are for providers that support them; an adapter whose provider has no equivalent ignores them.
|
|
94
|
+
|
|
95
|
+
| Field | Lettermint | SMTP, Microsoft Graph |
|
|
96
|
+
|---|---|---|
|
|
97
|
+
| `idempotency_key` | `Idempotency-Key`: the same key is sent once, so retrying after an uncertain failure cannot send twice | ignored |
|
|
98
|
+
| `tag`, `metadata` | stored with the message, returned in delivery webhooks | ignored |
|
|
99
|
+
| `track_opens`, `track_clicks` | per-message tracking; `None` keeps the project default | ignored |
|
|
100
|
+
| `require_tls` | `tls: enforced` | ignored; SMTP's own `encryption` applies |
|
|
101
|
+
|
|
102
|
+
### Errors
|
|
103
|
+
|
|
104
|
+
Every provider failure is an `AdapterError`. `status_code` is the provider's HTTP status when it answered with one, and `transient` says whether trying again later may succeed (timeouts, dropped connections, rate limits, server errors, SMTP 4xx replies). A transient failure while sending can mean the message went out before the connection broke: retry with the same `idempotency_key`.
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
try:
|
|
108
|
+
outbox.send_mail(message)
|
|
109
|
+
except AdapterError as exc:
|
|
110
|
+
if not exc.transient:
|
|
111
|
+
raise
|
|
112
|
+
... # retry later, same message, same idempotency_key
|
|
113
|
+
```
|
|
114
|
+
|
|
87
115
|
## Reading
|
|
88
116
|
|
|
89
117
|
```python
|
|
@@ -124,6 +152,10 @@ async def inbound(request: Request) -> None:
|
|
|
124
152
|
|
|
125
153
|
Responding is up to your app. Providers retry deliveries that get no 2xx, so the same message can arrive twice; `message.id` stays the same.
|
|
126
154
|
|
|
155
|
+
A correctly signed webhook for another event (a delivery report sent to the same URL) raises `UnsupportedWebhookError`, a subclass of `AdapterError` with the event name in `event`; answer it with a 2xx so the provider stops retrying. Fields the provider sends that `Message` has no place for — Lettermint's `route`, envelope `recipient`, `is_spam`, `authentication_results` and the event `id` — are in `message.provider_data`, as sent, without the body and attachment contents.
|
|
156
|
+
|
|
157
|
+
A Lettermint route can deliver large attachments as signed download links instead of inline. `parse_webhook()` downloads them by default; `FlowInbox.connect_lettermint(webhook_secret=..., download_attachments=False)` leaves their `content` empty and their `url` in `provider_data`, so a queued job can fetch them after the webhook has been answered.
|
|
158
|
+
|
|
127
159
|
## Lettermint
|
|
128
160
|
|
|
129
161
|
One adapter covers everything; each part needs only its own credential. Sending uses a project token (`lm_...`), `retrieve_mails()` a team token (`lm_team_...`) with the team's inbound routes as the mailboxes, and `parse_webhook()` the inbound route webhook's signing secret (`whsec_...`).
|
|
@@ -137,3 +169,28 @@ lettermint = LettermintAdapter(project_token="lm_...", team_token="lm_team_...",
|
|
|
137
169
|
inbox = FlowInbox(lettermint)
|
|
138
170
|
outbox = FlowOutbox(lettermint, sender=Address("noreply@acme.com"))
|
|
139
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.
|
|
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:
|
|
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
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
from flowbox._exceptions import AdapterError, MessageError, SignatureError
|
|
1
|
+
from flowbox._exceptions import AdapterError, MessageError, SignatureError, UnsupportedWebhookError
|
|
2
2
|
from flowbox._flowbox import FlowInbox, FlowOutbox
|
|
3
3
|
from flowbox._message import Address, Attachment, Message
|
|
4
4
|
|
|
@@ -11,4 +11,5 @@ __all__ = [
|
|
|
11
11
|
"Message",
|
|
12
12
|
"MessageError",
|
|
13
13
|
"SignatureError",
|
|
14
|
+
"UnsupportedWebhookError",
|
|
14
15
|
]
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AdapterError(Exception):
|
|
5
|
+
"""The provider could not do what was asked.
|
|
6
|
+
|
|
7
|
+
``status_code`` is the provider's HTTP status when it answered with one.
|
|
8
|
+
``transient`` is true when trying again later may succeed: a timeout, a
|
|
9
|
+
dropped connection, a rate limit or a server error. A transient failure on
|
|
10
|
+
send can also mean the provider accepted the message before the connection
|
|
11
|
+
broke, so retry with the same ``Message.idempotency_key``."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, message: str, *, status_code: int | None = None, transient: bool = False) -> None:
|
|
14
|
+
super().__init__(message)
|
|
15
|
+
self.status_code = status_code
|
|
16
|
+
self.transient = transient
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SignatureError(AdapterError):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class UnsupportedWebhookError(AdapterError):
|
|
24
|
+
"""A correctly signed webhook for an event this adapter does not translate
|
|
25
|
+
(a delivery report, say). Answer it with a 2xx so the provider stops retrying."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, message: str, *, event: str | None = None) -> None:
|
|
28
|
+
super().__init__(message)
|
|
29
|
+
self.event = event
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class MessageError(Exception):
|
|
33
|
+
pass
|
|
@@ -52,13 +52,20 @@ class FlowInbox[AdapterT: InboxAdapterABC | WebhookInboxAdapterABC]:
|
|
|
52
52
|
webhook_secret: str | None = None,
|
|
53
53
|
project_id: str | None = None,
|
|
54
54
|
timeout: float = 30.0,
|
|
55
|
+
download_attachments: bool = True,
|
|
55
56
|
) -> FlowInbox[LettermintAdapter]:
|
|
56
57
|
"""``team_token`` is for retrieve_mails(), ``webhook_secret`` (``whsec_...``)
|
|
57
|
-
for parse_webhook(); pass whichever this inbox uses.
|
|
58
|
+
for parse_webhook(); pass whichever this inbox uses. With
|
|
59
|
+
``download_attachments=False`` a webhook's attachments delivered by URL
|
|
60
|
+
keep empty content, their url in ``provider_data``."""
|
|
58
61
|
from flowbox.adapters import LettermintAdapter
|
|
59
62
|
|
|
60
63
|
adapter = LettermintAdapter(
|
|
61
|
-
team_token=team_token,
|
|
64
|
+
team_token=team_token,
|
|
65
|
+
webhook_secret=webhook_secret,
|
|
66
|
+
project_id=project_id,
|
|
67
|
+
timeout=timeout,
|
|
68
|
+
download_attachments=download_attachments,
|
|
62
69
|
)
|
|
63
70
|
return FlowInbox(adapter)
|
|
64
71
|
|
|
@@ -123,6 +130,24 @@ class FlowOutbox:
|
|
|
123
130
|
|
|
124
131
|
return cls(LettermintAdapter(project_token=project_token, route=route, timeout=timeout), sender)
|
|
125
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
|
+
|
|
126
151
|
@property
|
|
127
152
|
def adapter(self) -> OutboxAdapterABC:
|
|
128
153
|
return self._adapter
|
|
@@ -5,6 +5,7 @@ from dataclasses import dataclass, field
|
|
|
5
5
|
from datetime import datetime
|
|
6
6
|
from email.utils import formataddr, parseaddr
|
|
7
7
|
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
8
9
|
|
|
9
10
|
|
|
10
11
|
@dataclass(slots=True, frozen=True)
|
|
@@ -54,7 +55,26 @@ class Message:
|
|
|
54
55
|
html: str | None = None
|
|
55
56
|
attachments: list[Attachment] = field(default_factory=list)
|
|
56
57
|
headers: dict[str, str] = field(default_factory=dict)
|
|
58
|
+
#: Sending only. Providers that deduplicate (Lettermint) accept the same key
|
|
59
|
+
#: once, so a retry after an uncertain failure cannot send the mail twice.
|
|
60
|
+
#: SMTP has no such guarantee and ignores it.
|
|
61
|
+
idempotency_key: str | None = None
|
|
62
|
+
#: Sending only: a label for grouping messages in the provider's dashboard.
|
|
63
|
+
tag: str | None = None
|
|
64
|
+
#: Sending only: key-value pairs the provider stores with the message and
|
|
65
|
+
#: returns in its webhooks. Not added to the mail itself.
|
|
66
|
+
metadata: dict[str, str] = field(default_factory=dict)
|
|
67
|
+
#: Sending only: None leaves the provider's default in place.
|
|
68
|
+
track_opens: bool | None = None
|
|
69
|
+
track_clicks: bool | None = None
|
|
70
|
+
#: Sending only: refuse delivery to servers that do not offer TLS, where the
|
|
71
|
+
#: provider supports enforcing it.
|
|
72
|
+
require_tls: bool = False
|
|
57
73
|
#: Set by the adapter on retrieved mail: the provider's id for the message.
|
|
58
74
|
id: str | None = None
|
|
59
75
|
#: Set by the adapter on retrieved mail: when the provider received it.
|
|
60
76
|
received_at: datetime | None = None
|
|
77
|
+
#: Set by webhook adapters: the provider's own fields that have no place
|
|
78
|
+
#: above (routing, spam verdicts, authentication results), as the provider
|
|
79
|
+
#: sent them, minus the body and attachment contents already in the message.
|
|
80
|
+
provider_data: dict[str, Any] = field(default_factory=dict)
|
|
@@ -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",
|
|
@@ -12,7 +12,7 @@ from collections.abc import Mapping
|
|
|
12
12
|
from datetime import UTC, datetime, timedelta
|
|
13
13
|
from typing import Any
|
|
14
14
|
|
|
15
|
-
from flowbox._exceptions import AdapterError, SignatureError
|
|
15
|
+
from flowbox._exceptions import AdapterError, SignatureError, UnsupportedWebhookError
|
|
16
16
|
from flowbox._message import Address, Attachment, Message
|
|
17
17
|
from flowbox._mime import from_mime
|
|
18
18
|
from flowbox.adapters._abc import InboxAdapterABC, OutboxAdapterABC, WebhookInboxAdapterABC, require_sender
|
|
@@ -47,6 +47,7 @@ class LettermintAdapter(InboxAdapterABC, WebhookInboxAdapterABC, OutboxAdapterAB
|
|
|
47
47
|
base_url: str = _BASE_URL,
|
|
48
48
|
timeout: float = 30.0,
|
|
49
49
|
webhook_tolerance: int = 300,
|
|
50
|
+
download_attachments: bool = True,
|
|
50
51
|
) -> None:
|
|
51
52
|
super().__init__(driver_name="lettermint")
|
|
52
53
|
|
|
@@ -55,6 +56,10 @@ class LettermintAdapter(InboxAdapterABC, WebhookInboxAdapterABC, OutboxAdapterAB
|
|
|
55
56
|
self._webhook_secret = webhook_secret
|
|
56
57
|
#: How far, in seconds, a webhook's signed timestamp may be off: replay protection.
|
|
57
58
|
self._webhook_tolerance = webhook_tolerance
|
|
59
|
+
#: False leaves attachments delivered by URL undownloaded: their content
|
|
60
|
+
#: stays empty and provider_data keeps the url, to fetch later (in a
|
|
61
|
+
#: queued job, say) instead of inside the webhook request.
|
|
62
|
+
self._download_attachments = download_attachments
|
|
58
63
|
#: Limits get_mailboxes() to one project's routes; all projects otherwise.
|
|
59
64
|
self._project_id = project_id
|
|
60
65
|
#: The route outgoing mail is sent through; the project's default otherwise.
|
|
@@ -69,7 +74,13 @@ class LettermintAdapter(InboxAdapterABC, WebhookInboxAdapterABC, OutboxAdapterAB
|
|
|
69
74
|
if self._project_token is None:
|
|
70
75
|
raise AdapterError("sending through Lettermint needs a project token")
|
|
71
76
|
|
|
72
|
-
|
|
77
|
+
headers = {"x-lettermint-token": self._project_token}
|
|
78
|
+
if message.idempotency_key is not None:
|
|
79
|
+
headers["Idempotency-Key"] = message.idempotency_key
|
|
80
|
+
|
|
81
|
+
response = self._json("POST", "/send", headers, self._payload(message))
|
|
82
|
+
if not response.get("message_id"):
|
|
83
|
+
raise AdapterError("Lettermint accepted the message without returning its id", transient=True)
|
|
73
84
|
return str(response["message_id"])
|
|
74
85
|
|
|
75
86
|
def _payload(self, message: Message) -> dict[str, Any]:
|
|
@@ -89,9 +100,23 @@ class LettermintAdapter(InboxAdapterABC, WebhookInboxAdapterABC, OutboxAdapterAB
|
|
|
89
100
|
payload["html"] = message.html
|
|
90
101
|
if message.headers:
|
|
91
102
|
payload["headers"] = dict(message.headers)
|
|
103
|
+
if message.metadata:
|
|
104
|
+
payload["metadata"] = dict(message.metadata)
|
|
105
|
+
if message.tag is not None:
|
|
106
|
+
payload["tag"] = message.tag
|
|
92
107
|
if self._route is not None:
|
|
93
108
|
payload["route"] = self._route
|
|
94
109
|
|
|
110
|
+
settings: dict[str, Any] = {}
|
|
111
|
+
if message.track_opens is not None:
|
|
112
|
+
settings["track_opens"] = message.track_opens
|
|
113
|
+
if message.track_clicks is not None:
|
|
114
|
+
settings["track_clicks"] = message.track_clicks
|
|
115
|
+
if message.require_tls:
|
|
116
|
+
settings["tls"] = "enforced"
|
|
117
|
+
if settings:
|
|
118
|
+
payload["settings"] = settings
|
|
119
|
+
|
|
95
120
|
if message.attachments:
|
|
96
121
|
payload["attachments"] = [
|
|
97
122
|
{
|
|
@@ -149,8 +174,13 @@ class LettermintAdapter(InboxAdapterABC, WebhookInboxAdapterABC, OutboxAdapterAB
|
|
|
149
174
|
def parse_webhook(self, body: bytes, headers: Mapping[str, str]) -> Message:
|
|
150
175
|
"""Translates a ``message.inbound`` webhook from an inbound route.
|
|
151
176
|
|
|
177
|
+
Any other correctly signed event raises UnsupportedWebhookError.
|
|
152
178
|
Lettermint retries a delivery it got no 2xx for, with the same payload,
|
|
153
|
-
so the same message can arrive twice; its id stays the same.
|
|
179
|
+
so the same message can arrive twice; its id stays the same.
|
|
180
|
+
|
|
181
|
+
``provider_data`` holds the event as sent (``id``, ``event``, and in
|
|
182
|
+
``data`` the ``route``, ``recipient``, ``envelope``, ``is_spam`` and the
|
|
183
|
+
rest) without the body and attachment contents."""
|
|
154
184
|
self._verify_signature(body, headers)
|
|
155
185
|
|
|
156
186
|
try:
|
|
@@ -158,19 +188,45 @@ class LettermintAdapter(InboxAdapterABC, WebhookInboxAdapterABC, OutboxAdapterAB
|
|
|
158
188
|
except ValueError as exc:
|
|
159
189
|
raise AdapterError("Lettermint webhook body is not valid JSON") from exc
|
|
160
190
|
|
|
161
|
-
if not isinstance(event, dict)
|
|
162
|
-
|
|
163
|
-
|
|
191
|
+
if not isinstance(event, dict):
|
|
192
|
+
raise AdapterError("Lettermint webhook body is not a JSON object")
|
|
193
|
+
if event.get("event") != "message.inbound":
|
|
194
|
+
kind = event.get("event")
|
|
195
|
+
raise UnsupportedWebhookError(
|
|
196
|
+
f"expected a message.inbound webhook, got {kind!r}", event=kind if isinstance(kind, str) else None
|
|
197
|
+
)
|
|
164
198
|
|
|
165
|
-
|
|
199
|
+
data = event.get("data")
|
|
200
|
+
if not isinstance(data, dict):
|
|
201
|
+
raise AdapterError("Lettermint inbound webhook has no data object")
|
|
202
|
+
|
|
203
|
+
try:
|
|
204
|
+
message = self._inbound_message(data)
|
|
205
|
+
except (KeyError, TypeError, ValueError, AttributeError) as exc:
|
|
206
|
+
raise AdapterError(f"Lettermint inbound webhook is malformed: {exc!r}") from exc
|
|
207
|
+
|
|
208
|
+
message.provider_data = {**event, "data": self._without_contents(data)}
|
|
209
|
+
return message
|
|
210
|
+
|
|
211
|
+
@staticmethod
|
|
212
|
+
def _without_contents(data: dict[str, Any]) -> dict[str, Any]:
|
|
213
|
+
stripped = {key: value for key, value in data.items() if key != "body"}
|
|
214
|
+
if isinstance(data.get("attachments"), list):
|
|
215
|
+
stripped["attachments"] = [
|
|
216
|
+
{key: value for key, value in item.items() if key != "content"} if isinstance(item, dict) else item
|
|
217
|
+
for item in data["attachments"]
|
|
218
|
+
]
|
|
219
|
+
return stripped
|
|
166
220
|
|
|
167
221
|
def _verify_signature(self, body: bytes, headers: Mapping[str, str]) -> None:
|
|
168
222
|
"""``X-Lettermint-Signature: t=<unix time>,v1=<hex>``, where v1 is the
|
|
169
|
-
HMAC-SHA256 of ``"<t>.<body>"`` keyed with the whole ``whsec_`` secret.
|
|
223
|
+
HMAC-SHA256 of ``"<t>.<body>"`` keyed with the whole ``whsec_`` secret.
|
|
224
|
+
``X-Lettermint-Delivery``, when present, must carry the same timestamp."""
|
|
170
225
|
if self._webhook_secret is None:
|
|
171
226
|
raise AdapterError("verifying Lettermint webhooks needs the webhook signing secret")
|
|
172
227
|
|
|
173
228
|
signature = next((value for name, value in headers.items() if name.lower() == "x-lettermint-signature"), None)
|
|
229
|
+
delivery = next((value for name, value in headers.items() if name.lower() == "x-lettermint-delivery"), None)
|
|
174
230
|
if signature is None:
|
|
175
231
|
raise SignatureError("the request has no X-Lettermint-Signature header")
|
|
176
232
|
|
|
@@ -178,6 +234,8 @@ class LettermintAdapter(InboxAdapterABC, WebhookInboxAdapterABC, OutboxAdapterAB
|
|
|
178
234
|
timestamp, received = parts.get("t", ""), parts.get("v1", "")
|
|
179
235
|
if not timestamp.isdigit() or not received:
|
|
180
236
|
raise SignatureError("the X-Lettermint-Signature header is malformed")
|
|
237
|
+
if delivery is not None and delivery.strip() != timestamp:
|
|
238
|
+
raise SignatureError("the X-Lettermint-Delivery timestamp does not match the signature")
|
|
181
239
|
|
|
182
240
|
if abs(time.time() - int(timestamp)) > self._webhook_tolerance:
|
|
183
241
|
raise SignatureError("the webhook's signed timestamp is too old or too far ahead")
|
|
@@ -207,10 +265,12 @@ class LettermintAdapter(InboxAdapterABC, WebhookInboxAdapterABC, OutboxAdapterAB
|
|
|
207
265
|
|
|
208
266
|
def _inbound_attachment(self, value: dict[str, Any]) -> Attachment:
|
|
209
267
|
"""Small files come inline as base64; a route set to deliver attachments
|
|
210
|
-
by URL sends a signed download link instead, valid for a limited time
|
|
268
|
+
by URL sends a signed download link instead, valid for a limited time;
|
|
269
|
+
it is downloaded here unless the adapter was built with
|
|
270
|
+
``download_attachments=False``."""
|
|
211
271
|
if value.get("content") is not None:
|
|
212
272
|
content = base64.b64decode(value["content"])
|
|
213
|
-
elif value.get("url"):
|
|
273
|
+
elif value.get("url") and self._download_attachments:
|
|
214
274
|
content = self._download(value["url"])
|
|
215
275
|
else:
|
|
216
276
|
content = b""
|
|
@@ -230,7 +290,11 @@ class LettermintAdapter(InboxAdapterABC, WebhookInboxAdapterABC, OutboxAdapterAB
|
|
|
230
290
|
content: bytes = response.read()
|
|
231
291
|
return content
|
|
232
292
|
except (urllib.error.URLError, OSError) as exc:
|
|
233
|
-
|
|
293
|
+
status_code = exc.code if isinstance(exc, urllib.error.HTTPError) else None
|
|
294
|
+
transient = status_code is None or status_code == 429 or status_code >= 500
|
|
295
|
+
raise AdapterError(
|
|
296
|
+
f"could not download Lettermint attachment: {exc}", status_code=status_code, transient=transient
|
|
297
|
+
) from exc
|
|
234
298
|
|
|
235
299
|
def _resolve_route_id(self, mailbox: str) -> str:
|
|
236
300
|
if self._route_ids is None or mailbox not in self._route_ids:
|
|
@@ -272,10 +336,10 @@ class LettermintAdapter(InboxAdapterABC, WebhookInboxAdapterABC, OutboxAdapterAB
|
|
|
272
336
|
try:
|
|
273
337
|
decoded = json.loads(body)
|
|
274
338
|
except ValueError as exc:
|
|
275
|
-
raise AdapterError(f"Lettermint returned invalid JSON for {method} {path}") from exc
|
|
339
|
+
raise AdapterError(f"Lettermint returned invalid JSON for {method} {path}", transient=True) from exc
|
|
276
340
|
|
|
277
341
|
if not isinstance(decoded, dict):
|
|
278
|
-
raise AdapterError(f"Lettermint returned unexpected JSON for {method} {path}")
|
|
342
|
+
raise AdapterError(f"Lettermint returned unexpected JSON for {method} {path}", transient=True)
|
|
279
343
|
return decoded
|
|
280
344
|
|
|
281
345
|
def _request(
|
|
@@ -299,6 +363,10 @@ class LettermintAdapter(InboxAdapterABC, WebhookInboxAdapterABC, OutboxAdapterAB
|
|
|
299
363
|
return body
|
|
300
364
|
except urllib.error.HTTPError as exc:
|
|
301
365
|
detail = exc.read().decode("utf-8", errors="replace")
|
|
302
|
-
raise AdapterError(
|
|
366
|
+
raise AdapterError(
|
|
367
|
+
f"Lettermint {method} {path} failed with HTTP {exc.code}: {detail}",
|
|
368
|
+
status_code=exc.code,
|
|
369
|
+
transient=exc.code == 429 or exc.code >= 500,
|
|
370
|
+
) from exc
|
|
303
371
|
except (urllib.error.URLError, OSError) as exc:
|
|
304
|
-
raise AdapterError(f"could not reach Lettermint: {exc}") from exc
|
|
372
|
+
raise AdapterError(f"could not reach Lettermint: {exc}", transient=True) from exc
|