cairnpost 0.1.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.
- cairnpost-0.1.0/.gitignore +29 -0
- cairnpost-0.1.0/CHANGELOG.md +35 -0
- cairnpost-0.1.0/LICENSE +21 -0
- cairnpost-0.1.0/PKG-INFO +469 -0
- cairnpost-0.1.0/README.md +450 -0
- cairnpost-0.1.0/pyproject.toml +59 -0
- cairnpost-0.1.0/src/cairnpost/__init__.py +96 -0
- cairnpost-0.1.0/src/cairnpost/_answer.py +28 -0
- cairnpost-0.1.0/src/cairnpost/_batch.py +60 -0
- cairnpost-0.1.0/src/cairnpost/_client.py +175 -0
- cairnpost-0.1.0/src/cairnpost/_codes.py +61 -0
- cairnpost-0.1.0/src/cairnpost/_deliveries.py +62 -0
- cairnpost-0.1.0/src/cairnpost/_email.py +183 -0
- cairnpost-0.1.0/src/cairnpost/_emails.py +133 -0
- cairnpost-0.1.0/src/cairnpost/_errors.py +202 -0
- cairnpost-0.1.0/src/cairnpost/_events.py +117 -0
- cairnpost-0.1.0/src/cairnpost/_message.py +204 -0
- cairnpost-0.1.0/src/cairnpost/_pages.py +50 -0
- cairnpost-0.1.0/src/cairnpost/_parse.py +15 -0
- cairnpost-0.1.0/src/cairnpost/_payload.py +76 -0
- cairnpost-0.1.0/src/cairnpost/_problem.py +55 -0
- cairnpost-0.1.0/src/cairnpost/_read.py +166 -0
- cairnpost-0.1.0/src/cairnpost/_received.py +173 -0
- cairnpost-0.1.0/src/cairnpost/_status.py +148 -0
- cairnpost-0.1.0/src/cairnpost/_suppressions.py +126 -0
- cairnpost-0.1.0/src/cairnpost/_templates.py +177 -0
- cairnpost-0.1.0/src/cairnpost/_transport.py +271 -0
- cairnpost-0.1.0/src/cairnpost/_verify.py +176 -0
- cairnpost-0.1.0/src/cairnpost/_version.py +3 -0
- cairnpost-0.1.0/src/cairnpost/_webhooks.py +255 -0
- cairnpost-0.1.0/src/cairnpost/py.typed +0 -0
- cairnpost-0.1.0/tests/__init__.py +0 -0
- cairnpost-0.1.0/tests/integration/__init__.py +0 -0
- cairnpost-0.1.0/tests/integration/live_sending.py +255 -0
- cairnpost-0.1.0/tests/integration/live_webhooks.py +244 -0
- cairnpost-0.1.0/tests/integration/server.py +58 -0
- cairnpost-0.1.0/tests/stand.py +97 -0
- cairnpost-0.1.0/tests/test_admin.py +363 -0
- cairnpost-0.1.0/tests/test_answers.py +221 -0
- cairnpost-0.1.0/tests/test_client.py +201 -0
- cairnpost-0.1.0/tests/test_emails.py +389 -0
- cairnpost-0.1.0/tests/test_errors.py +354 -0
- cairnpost-0.1.0/tests/test_hardening.py +174 -0
- cairnpost-0.1.0/tests/test_verify.py +300 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Build output, caches and environments
|
|
2
|
+
dist/
|
|
3
|
+
build/
|
|
4
|
+
*.egg-info/
|
|
5
|
+
__pycache__/
|
|
6
|
+
*.py[cod]
|
|
7
|
+
.venv/
|
|
8
|
+
.mypy_cache/
|
|
9
|
+
.ruff_cache/
|
|
10
|
+
uv.lock
|
|
11
|
+
|
|
12
|
+
# Local env overrides
|
|
13
|
+
.env
|
|
14
|
+
.env.local
|
|
15
|
+
|
|
16
|
+
# Editor / OS cruft
|
|
17
|
+
.DS_Store
|
|
18
|
+
.idea/
|
|
19
|
+
.vscode/
|
|
20
|
+
|
|
21
|
+
# Working documents and assistant rules stay out of the repository
|
|
22
|
+
.claude/
|
|
23
|
+
CLAUDE.md
|
|
24
|
+
PLAN.md
|
|
25
|
+
STATUS.md
|
|
26
|
+
NOTES.md
|
|
27
|
+
COMMIT_MESSAGE.md
|
|
28
|
+
.archive/
|
|
29
|
+
graphify-out/
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
Every change a user of this client can notice is written here. The format is
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and versions follow
|
|
5
|
+
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.1.0] - 2026-11-17
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- The client, for CairnPost 0.1.1: `CairnPost(base_url, api_key)`, on the
|
|
14
|
+
standard library alone, typed, for Python 3.11 and later.
|
|
15
|
+
- `emails.send` and `emails.get`: send an `Email` to one address or several
|
|
16
|
+
(`to`, `cc`, `bcc`), with files (`attachments`), from a template
|
|
17
|
+
(`template`) or at a later time (`scheduled_at`), and read what became of
|
|
18
|
+
it at each address. An `idempotency_key` makes a repeated send one email.
|
|
19
|
+
- `emails.send_batch`: several emails in one request, each with its own
|
|
20
|
+
result; `failed` counts those that did not go.
|
|
21
|
+
- `emails.cancel` and `emails.reschedule` for an email that waits, and
|
|
22
|
+
`emails.file` to read back a file the server keeps.
|
|
23
|
+
- `CairnPostError`, with the server's `code` and `detail`, `retryable` and
|
|
24
|
+
`retry_after`; `TransportError` for a call that got no answer;
|
|
25
|
+
`may_have_sent`, `is_not_found` and `is_wrong_address` to ask what an
|
|
26
|
+
error means. The client never retries by itself and follows no redirect.
|
|
27
|
+
- `Verifier`: checks a webhook's signature and timestamp and reads it,
|
|
28
|
+
every type the server sends.
|
|
29
|
+
- With an admin key: `suppressions`, `webhooks` (with deliveries, a test,
|
|
30
|
+
secret rotation and resume), `templates`, `received` (the emails that
|
|
31
|
+
come in) and `captured`.
|
|
32
|
+
- `health` and `limits`.
|
|
33
|
+
|
|
34
|
+
[Unreleased]: https://github.com/mettjs/cairnpost-python/compare/v0.1.0...HEAD
|
|
35
|
+
[0.1.0]: https://github.com/mettjs/cairnpost-python/releases/tag/v0.1.0
|
cairnpost-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Michael Ramirez
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
cairnpost-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: cairnpost
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The Python client for CairnPost, a self-hostable gateway for transactional email.
|
|
5
|
+
Project-URL: Homepage, https://github.com/mettjs/cairnpost-python
|
|
6
|
+
Project-URL: Changelog, https://github.com/mettjs/cairnpost-python/blob/main/CHANGELOG.md
|
|
7
|
+
Project-URL: Issues, https://github.com/mettjs/cairnpost-python/issues
|
|
8
|
+
Author: Michael Ramirez
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: cairnpost,email,transactional,webhooks
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Topic :: Communications :: Email
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.11
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
<p align="center">
|
|
21
|
+
<picture>
|
|
22
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/mettjs/cairnpost-python/main/.github/logo-dark.svg">
|
|
23
|
+
<img src="https://raw.githubusercontent.com/mettjs/cairnpost-python/main/.github/logo-light.svg" alt="CairnPost" width="330" height="72">
|
|
24
|
+
</picture>
|
|
25
|
+
</p>
|
|
26
|
+
|
|
27
|
+
# cairnpost-python
|
|
28
|
+
|
|
29
|
+
The Python client for [CairnPost](https://github.com/mettjs/CairnPost), a
|
|
30
|
+
self-hostable gateway for transactional email. It sends email, reads what
|
|
31
|
+
became of it, manages suppressions, templates and webhook endpoints, reads
|
|
32
|
+
the email that comes in, and verifies the webhooks CairnPost sends.
|
|
33
|
+
|
|
34
|
+
It uses the standard library only, is fully typed, and needs Python 3.11 or
|
|
35
|
+
later.
|
|
36
|
+
|
|
37
|
+
**Status: early.** This is 0.1.0, for CairnPost 0.1.1. The
|
|
38
|
+
[changelog](https://github.com/mettjs/cairnpost-python/blob/main/CHANGELOG.md) says
|
|
39
|
+
what exists.
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
pip install cairnpost
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Send an email
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import os
|
|
49
|
+
from cairnpost import CairnPost, Email
|
|
50
|
+
|
|
51
|
+
client = CairnPost("https://mail.example.com", os.environ["CAIRNPOST_API_KEY"])
|
|
52
|
+
|
|
53
|
+
sent = client.emails.send(
|
|
54
|
+
Email(
|
|
55
|
+
from_="Example <hello@example.com>",
|
|
56
|
+
to=["ana@example.org"],
|
|
57
|
+
subject="Welcome",
|
|
58
|
+
text="Glad you are here.",
|
|
59
|
+
idempotency_key="welcome-user-42",
|
|
60
|
+
)
|
|
61
|
+
)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`sent.id` is the email's id. `html`, `text` or both; `cc`, `bcc`, `reply_to`
|
|
65
|
+
and `headers` are optional. The sender is `from_`, since `from` is a word of
|
|
66
|
+
Python's own; `to`, `cc` and `bcc` are lists.
|
|
67
|
+
|
|
68
|
+
Files go with an email as `attachments`:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from cairnpost import Attachment
|
|
72
|
+
|
|
73
|
+
Email(
|
|
74
|
+
# ...
|
|
75
|
+
attachments=[
|
|
76
|
+
Attachment(filename="invoice.pdf", content=pdf), # bytes
|
|
77
|
+
# Shown in the HTML body as <img src="cid:logo">.
|
|
78
|
+
Attachment(filename="logo.png", content=logo, content_id="logo"),
|
|
79
|
+
],
|
|
80
|
+
)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`content_type` is told from the filename when left out. The server sets how
|
|
84
|
+
many files an email may carry and how large they may be in all (10 files and
|
|
85
|
+
10 MiB by default). It keeps a file only where it is set to keep what emails
|
|
86
|
+
say, for as long, and while an email waits to be sent; `emails.file` reads
|
|
87
|
+
one back. Whether a file with a `content_id` can be sent depends on the
|
|
88
|
+
server's mail provider.
|
|
89
|
+
|
|
90
|
+
An email may name several addresses in `to`, `cc` and `bcc` (50 in all,
|
|
91
|
+
unless the server is set otherwise). It is still one email with one id. An
|
|
92
|
+
address on the sending domain's suppression list is left out and the email
|
|
93
|
+
goes to the others: `sent.suppressed` names who was left out, as
|
|
94
|
+
`message.suppressed` does when the email is read later. The send is an error
|
|
95
|
+
when nobody in `to` or `cc` is left: a `bcc` alone is not sent.
|
|
96
|
+
|
|
97
|
+
**Use an `idempotency_key` for anything you may retry.** The same key with
|
|
98
|
+
the same content, sent again, is the same email: the retry answers the first
|
|
99
|
+
one's id and sends nothing. A key is printable ASCII with no space at either
|
|
100
|
+
end; an empty one is refused, since it would be no key at all.
|
|
101
|
+
|
|
102
|
+
Several emails go in one request with `send_batch`:
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from cairnpost import failed
|
|
106
|
+
|
|
107
|
+
results = client.emails.send_batch(emails, idempotency_key="welcome-run-42")
|
|
108
|
+
# It raises when the batch was refused whole (one email could never be
|
|
109
|
+
# sent, say): nothing was sent then.
|
|
110
|
+
for i, r in enumerate(results):
|
|
111
|
+
if r.error:
|
|
112
|
+
# Email i did not go: the same CairnPostError a send would raise.
|
|
113
|
+
continue
|
|
114
|
+
# r.sent.id
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
An answer says the batch was taken, not that every email went: read each
|
|
118
|
+
result, or count with `failed(results)`. With an `idempotency_key`, the same
|
|
119
|
+
batch sent again (the same emails in the same order) sends only what did not
|
|
120
|
+
go. Each failed email's `retry_after` is its own. The server sets how many
|
|
121
|
+
emails a batch may hold (100 by default) and how long it may take; a server
|
|
122
|
+
given more than its default minute wants a client with a longer `timeout`.
|
|
123
|
+
|
|
124
|
+
An email can be asked for now and sent later:
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
from datetime import UTC, datetime, timedelta
|
|
128
|
+
|
|
129
|
+
sent = client.emails.send(Email(..., scheduled_at=datetime.now(UTC) + timedelta(days=1)))
|
|
130
|
+
# sent.scheduled_at is when it goes; nothing was sent yet.
|
|
131
|
+
|
|
132
|
+
client.emails.reschedule(sent.id, datetime.now(UTC) + timedelta(days=2))
|
|
133
|
+
client.emails.cancel(sent.id)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
A time given to the client must have a zone (`tzinfo`): one without is
|
|
137
|
+
refused before anything is sent. Every time the client answers is in UTC.
|
|
138
|
+
|
|
139
|
+
Until its time the email's `state` is `State.SCHEDULED`; from then on it is
|
|
140
|
+
an email like any other, under the same id. `cancel` and `reschedule` raise a
|
|
141
|
+
`CairnPostError` with the code `not_scheduled` once the email is being sent,
|
|
142
|
+
was sent or was cancelled. The server keeps what a waiting email says, and
|
|
143
|
+
its files, until it is sent or cancelled. An address suppressed by the time
|
|
144
|
+
the email goes is left out; with nobody left in `to` or `cc`, the email is
|
|
145
|
+
cancelled and `message.reason` says `"suppressed"`. Revoking an API key
|
|
146
|
+
cancels the emails it asked for that still wait. The emails of a batch may
|
|
147
|
+
each have a `scheduled_at`. An `idempotency_key` is remembered for a day from
|
|
148
|
+
the asking, not until the email goes.
|
|
149
|
+
|
|
150
|
+
## Templates
|
|
151
|
+
|
|
152
|
+
A template is an email the server keeps, written once with variables as
|
|
153
|
+
`{{name}}`. An admin key keeps one, and any key sends from it:
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
from cairnpost import UseTemplate
|
|
157
|
+
|
|
158
|
+
admin.templates.create(
|
|
159
|
+
name="welcome",
|
|
160
|
+
subject="Welcome, {{name}}",
|
|
161
|
+
html="<p>Your code is <b>{{code}}</b></p>",
|
|
162
|
+
text="Your code is {{code}}",
|
|
163
|
+
defaults={"name": "there"},
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
client.emails.send(
|
|
167
|
+
Email(
|
|
168
|
+
from_="app@example.com",
|
|
169
|
+
to=["ana@example.org"],
|
|
170
|
+
template=UseTemplate(name="welcome", variables={"code": "4821"}),
|
|
171
|
+
)
|
|
172
|
+
)
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Leave `html` and `text` out with a `template`; a `subject` given with it is
|
|
176
|
+
used instead of the template's. A value is written as it is in the subject
|
|
177
|
+
and the text and escaped in the HTML, so it is never markup there: keep
|
|
178
|
+
attributes in quotes (`href="{{link}}"`). A variable with no default must be
|
|
179
|
+
given, and a value for a variable the template does not name is refused:
|
|
180
|
+
both are a `CairnPostError` with status 422, and nothing is sent. The email
|
|
181
|
+
is filled when it is asked for, so one that waits (`scheduled_at`) keeps what
|
|
182
|
+
it was filled with whatever becomes of the template. A template belongs to a
|
|
183
|
+
sending domain or, with no `domain` and a key bound to none, serves every
|
|
184
|
+
domain; a send gets its own domain's template of that name first.
|
|
185
|
+
|
|
186
|
+
## When a send fails
|
|
187
|
+
|
|
188
|
+
The client never retries by itself. The error says what happened:
|
|
189
|
+
|
|
190
|
+
```python
|
|
191
|
+
from cairnpost import CairnPostError, ErrorCode, TransportError, may_have_sent
|
|
192
|
+
|
|
193
|
+
try:
|
|
194
|
+
sent = client.emails.send(email)
|
|
195
|
+
# Sent. Keep sent.id.
|
|
196
|
+
except (CairnPostError, TransportError) as err:
|
|
197
|
+
if isinstance(err, CairnPostError) and err.code is ErrorCode.RECIPIENT_SUPPRESSED:
|
|
198
|
+
# The address bounced for good, complained, or was blocked by hand
|
|
199
|
+
# (everyone in to and cc, if the email named several). Nothing was
|
|
200
|
+
# sent now, and nothing will be: stop sending to it, and do not
|
|
201
|
+
# retry. If err.email_id is set, an earlier try under the same key
|
|
202
|
+
# got no answer and may have gone: emails.get(err.email_id) says
|
|
203
|
+
# what became of it.
|
|
204
|
+
...
|
|
205
|
+
elif may_have_sent(err):
|
|
206
|
+
# It is not known whether the email went. Try again later with the
|
|
207
|
+
# same idempotency_key, and only with it. Ask this before the
|
|
208
|
+
# cases below: they mean "nothing was sent" only after it.
|
|
209
|
+
...
|
|
210
|
+
elif isinstance(err, CairnPostError) and err.retryable:
|
|
211
|
+
# Nothing was sent. Try again, after err.retry_after if it is set.
|
|
212
|
+
...
|
|
213
|
+
else:
|
|
214
|
+
# The request is at fault, or the key is. Trying again will not help.
|
|
215
|
+
...
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
| Error | Meaning |
|
|
219
|
+
|---|---|
|
|
220
|
+
| `CairnPostError`, status 422 | The request is at fault and will never succeed. `recipient_suppressed` is one of them. |
|
|
221
|
+
| `CairnPostError`, 409 `invalid_idempotent_request` | The key was used for a different email, which was sent. |
|
|
222
|
+
| `CairnPostError`, 409 `concurrent_idempotent_requests`, 408 `request_incomplete`, 429, 503 | Nothing was sent. Try again, after `retry_after` (seconds) when set. The 408 is a request that did not arrive whole in time, a 503 can be a server busy with other large emails. |
|
|
223
|
+
| `CairnPostError`, 502 `upstream_unknown` | The mail provider did not answer. The email may have gone. |
|
|
224
|
+
| `CairnPostError`, any other 5xx but the 503s above, or a 408 that is not CairnPost's own | The server failed after it began, or something in between answered for it (a proxy's 502 or 408). The email may have gone. |
|
|
225
|
+
| `TransportError` | The server was not reached, its answer never came or was not CairnPost's, or the call ran out of time; `reason` says which, and `cause_kind` names the kind of error underneath (`ConnectionRefusedError`, say). For a send, the email may have gone. |
|
|
226
|
+
| `ValueError` | What was given to the client cannot be sent as it is (an `idempotency_key` a header cannot carry, a time with no zone, a lone address where a list belongs). Nothing was sent. |
|
|
227
|
+
|
|
228
|
+
`may_have_sent` is true for the fourth, fifth and sixth, and for a
|
|
229
|
+
`recipient_suppressed` that carries an `email_id`: nothing was sent now, but
|
|
230
|
+
an earlier try under the same key got no answer and may have gone. That one
|
|
231
|
+
is not retried: the address is suppressed. For the others, the retry that
|
|
232
|
+
`may_have_sent` asks for is not a promise of one email: when the mail
|
|
233
|
+
provider's answer was lost, the server lets a retry through after a short
|
|
234
|
+
wait, because an email that arrives twice is better than one that never
|
|
235
|
+
does.
|
|
236
|
+
|
|
237
|
+
On a `CairnPostError`, `code` is the server's name for the error (an
|
|
238
|
+
`ErrorCode`, which is also a `str`), `detail` its sentence for a person, and
|
|
239
|
+
`email_id`, when set, the email's id on the server: `emails.get` says what
|
|
240
|
+
became of it. `code` and `detail` are `None` when the answer was not
|
|
241
|
+
CairnPost's own. No error holds the email's subject or body, or the API key;
|
|
242
|
+
an answer that is not CairnPost's own is never quoted, and the standard
|
|
243
|
+
library's own error is not kept as a cause, since it can hold what the other
|
|
244
|
+
side answered. `retryable` is also true of a 409 `changed_meanwhile`, which
|
|
245
|
+
a template change can meet: read the template and try again.
|
|
246
|
+
|
|
247
|
+
The client does not follow redirects, which would turn a send into a request
|
|
248
|
+
with no email in it: give it the server's own address. It makes each call on
|
|
249
|
+
a connection of its own, and does not read the proxy settings of the
|
|
250
|
+
environment. An API key is sent without the spaces or newline around it, and
|
|
251
|
+
is not shown when a client is printed.
|
|
252
|
+
|
|
253
|
+
A call may take two and a half minutes, longer than the server takes for its
|
|
254
|
+
slowest answer: a batch, which may take 30 seconds to arrive, starts emails
|
|
255
|
+
for a minute and then waits for the mail provider on the last of them, two
|
|
256
|
+
minutes in all. If you set `timeout`, keep it above that (and higher still
|
|
257
|
+
if the server's send or batch timeout was raised): a client that gives up
|
|
258
|
+
first cannot know whether its emails went.
|
|
259
|
+
|
|
260
|
+
The client blocks while it calls, and may be used from several threads at
|
|
261
|
+
once. In `asyncio` code, call it through `asyncio.to_thread`.
|
|
262
|
+
|
|
263
|
+
## What became of an email
|
|
264
|
+
|
|
265
|
+
```python
|
|
266
|
+
m = client.emails.get(id)
|
|
267
|
+
print(
|
|
268
|
+
m.state
|
|
269
|
+
) # scheduled, cancelled, sending, sent, deferred, delivered, bounced, complained, failed, unknown
|
|
270
|
+
for r in m.recipients:
|
|
271
|
+
print(r.address, r.kind, r.state) # each address has its own outcome
|
|
272
|
+
for e in m.events:
|
|
273
|
+
print(e.to, e.type, e.at, e.code, e.reason)
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
`m.to` and `m.state` are the first address and what became of the email
|
|
277
|
+
there; for an email to several, read `m.recipients`: `failed` at one address
|
|
278
|
+
does not say the email went to nobody.
|
|
279
|
+
|
|
280
|
+
A send key sees the emails it sent; an admin key sees any, or its sending
|
|
281
|
+
domain's if it is bound to one. `is_not_found(err)` says there is no such
|
|
282
|
+
email: the id is wrong, another key's, or older than the server keeps
|
|
283
|
+
records. `is_wrong_address(err)` says something else: the request reached no
|
|
284
|
+
route of CairnPost's, so the base URL given to the client is most likely
|
|
285
|
+
wrong, and no record is known to be missing. `client.health()` fails the
|
|
286
|
+
same way on a wrong base URL, so it is the call to check a configuration
|
|
287
|
+
with. (Both need the server's own error answers to arrive: a proxy that puts
|
|
288
|
+
its own page in place of every 404 makes a missing record read as a wrong
|
|
289
|
+
address.) `m.content` is what the email said, set only when the server keeps
|
|
290
|
+
content and the key is an admin key.
|
|
291
|
+
|
|
292
|
+
## Webhooks
|
|
293
|
+
|
|
294
|
+
CairnPost tells your application what becomes of its emails by posting to a
|
|
295
|
+
URL of yours. Each webhook is signed; verify it before you trust it:
|
|
296
|
+
|
|
297
|
+
```python
|
|
298
|
+
import os
|
|
299
|
+
from http.server import BaseHTTPRequestHandler
|
|
300
|
+
from cairnpost import BounceType, EventType, Verifier, WebhookError
|
|
301
|
+
|
|
302
|
+
verifier = Verifier(os.environ["CAIRNPOST_WEBHOOK_SECRET"])
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
class Hook(BaseHTTPRequestHandler):
|
|
306
|
+
def do_POST(self):
|
|
307
|
+
body = self.rfile.read(min(int(self.headers.get("Content-Length") or 0), 1 << 20))
|
|
308
|
+
try:
|
|
309
|
+
event = verifier.verify(self.headers, body) # the body exactly as it arrived
|
|
310
|
+
except WebhookError: # a TypeError is a mistake in this code, not a bad webhook
|
|
311
|
+
self.send_error(401, "not a CairnPost webhook")
|
|
312
|
+
return
|
|
313
|
+
if event.type == EventType.BOUNCED and event.email.bounce_type == BounceType.PERMANENT:
|
|
314
|
+
... # The address will never take mail.
|
|
315
|
+
elif event.type == EventType.COMPLAINED:
|
|
316
|
+
... # Its owner marked the email as spam.
|
|
317
|
+
self.send_response(204)
|
|
318
|
+
self.end_headers()
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
- `verify` takes the headers as a dict or as a web framework gives them
|
|
322
|
+
(`request.headers` in Flask, Django, FastAPI and Starlette), and the body
|
|
323
|
+
as bytes or as the text they are. Give it the body before anything parses
|
|
324
|
+
it: a body read as JSON and written again is not the body that was signed.
|
|
325
|
+
Limit how much of a body you read (1 MiB is plenty).
|
|
326
|
+
- It raises a `WebhookError` whose `reason` is `"signature"` for a wrong
|
|
327
|
+
signature, `"unsigned"` for missing headers, and `"stale"` for a timestamp
|
|
328
|
+
more than five minutes from now, which is what stops a captured webhook
|
|
329
|
+
being replayed.
|
|
330
|
+
- `event.id` is the same on every try of a webhook. CairnPost retries one
|
|
331
|
+
that was not answered with a 2xx, and may send one twice: act once per id.
|
|
332
|
+
- `event.email` is set for `email.delivered`, `email.delivery_delayed`,
|
|
333
|
+
`email.bounced`, `email.complained` and `email.failed`, and
|
|
334
|
+
`event.email.bounce_type` for `email.bounced`; a webhook of those types
|
|
335
|
+
that lacks them, or does not say when its email was made
|
|
336
|
+
(`event.email.created_at`), is refused (`"payload"`). `event.email` is `None`
|
|
337
|
+
for `webhook.test`, the webhook sent to try an endpoint out. A type this
|
|
338
|
+
client does not know is passed on as it is, with what could be read of it.
|
|
339
|
+
- `event.email.to` holds the one address the event is about, also when the
|
|
340
|
+
email went to several; `event.email.id` is the email's one id.
|
|
341
|
+
- `email.received` (`EventType.RECEIVED`) tells of an email that came for
|
|
342
|
+
one of your addresses, where the server takes them. It is about no email
|
|
343
|
+
you sent: `event.received` says who it is from and for, when it came, and
|
|
344
|
+
the id to read it by (see "Receiving email"). An endpoint that hears about every event
|
|
345
|
+
gets these too.
|
|
346
|
+
- `address.suppressed` (`EventType.ADDRESS_SUPPRESSED`) tells of an address
|
|
347
|
+
suppressed because of a bounce or a complaint about an email the server
|
|
348
|
+
has no record of. It names no email: `event.suppression` holds the sending
|
|
349
|
+
domain, the address and the reason (`Reason.BOUNCE` or
|
|
350
|
+
`Reason.COMPLAINT`). Treat it as you treat an `email.bounced` or an
|
|
351
|
+
`email.complained` with `suppressed` set.
|
|
352
|
+
- Of the three bounce types only `BounceType.PERMANENT` says the address is
|
|
353
|
+
at fault. `BounceType.POLICY` is a refusal over the sender (a failed
|
|
354
|
+
signature, a blocklist); the address may be perfectly good.
|
|
355
|
+
- `event.email.suppressed` says CairnPost will now refuse to send to that
|
|
356
|
+
address from that sending domain.
|
|
357
|
+
|
|
358
|
+
The signature is the Standard Webhooks scheme, which Svix also uses, so any
|
|
359
|
+
verifier for either works too.
|
|
360
|
+
|
|
361
|
+
## Receiving email
|
|
362
|
+
|
|
363
|
+
A server set up to take the emails that come for its domains' addresses
|
|
364
|
+
keeps each for a time (7 days by default) and tells your endpoint with an
|
|
365
|
+
`email.received` webhook. Read it with an admin key:
|
|
366
|
+
|
|
367
|
+
```python
|
|
368
|
+
if event.type == EventType.RECEIVED:
|
|
369
|
+
got = admin.received.get(event.received.id)
|
|
370
|
+
# got.content.subject, .text, .html, .attachments ...
|
|
371
|
+
pdf = admin.received.file(got.id, 1) # its first file
|
|
372
|
+
raw = admin.received.raw(got.id) # every byte, as it came
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
A stranger wrote it: treat every part as untrusted, and never show its HTML
|
|
376
|
+
as a page. `got.from_` is what the sending server said and
|
|
377
|
+
`got.content.from_` what the email says of itself; either can be made up.
|
|
378
|
+
`content.partial` says some of it could not be read as it was written (a
|
|
379
|
+
charset the server does not know); `received.raw` always has all of it.
|
|
380
|
+
`received.list` and `received.all` list what is kept, and `received.delete`
|
|
381
|
+
deletes one before its time. `is_not_found` says an email's time is up.
|
|
382
|
+
|
|
383
|
+
## With an admin key
|
|
384
|
+
|
|
385
|
+
```python
|
|
386
|
+
from cairnpost import DeliveryState, Reason
|
|
387
|
+
|
|
388
|
+
# Webhook endpoints. The secret is said only here: keep it.
|
|
389
|
+
w = admin.webhooks.create(
|
|
390
|
+
"https://app.example.com/webhooks/cairnpost",
|
|
391
|
+
events=[EventType.BOUNCED, EventType.COMPLAINED],
|
|
392
|
+
)
|
|
393
|
+
print(w.secret)
|
|
394
|
+
|
|
395
|
+
res = admin.webhooks.test(w.id) # sends a webhook.test now
|
|
396
|
+
|
|
397
|
+
# A new signing secret, said only here. Until w.previous_secret_until the
|
|
398
|
+
# server signs with the old one too: change the application's secret
|
|
399
|
+
# within that time. If it is None, the old one has stopped already.
|
|
400
|
+
w = admin.webhooks.rotate_secret(w.id)
|
|
401
|
+
|
|
402
|
+
admin.webhooks.update(w.id, enabled=False)
|
|
403
|
+
|
|
404
|
+
for d in admin.webhooks.all_deliveries(w.id, DeliveryState.FAILED):
|
|
405
|
+
admin.webhooks.retry_delivery(w.id, d.id)
|
|
406
|
+
|
|
407
|
+
# The suppression list.
|
|
408
|
+
for s in admin.suppressions.all("example.com"):
|
|
409
|
+
print(s.address, s.reason)
|
|
410
|
+
admin.suppressions.add("example.com", "ana@example.org", "asked to stop")
|
|
411
|
+
admin.suppressions.lift("example.com", "ana@example.org")
|
|
412
|
+
admin.suppressions.lift_all("example.com", Reason.BOUNCE)
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
| Calls | Do |
|
|
416
|
+
|---|---|
|
|
417
|
+
| `webhooks.create`, `list`, `get`, `update`, `delete` | Manage the URLs told what becomes of emails. |
|
|
418
|
+
| `webhooks.test` | Send an endpoint a signed `webhook.test` and say how it answered. |
|
|
419
|
+
| `webhooks.rotate_secret` | Give an endpoint a new signing secret; the old one still signs for a day, unless the server is set otherwise. |
|
|
420
|
+
| `webhooks.resume` | End an endpoint's pause, and have what it is owed sent. |
|
|
421
|
+
| `webhooks.deliveries`, `all_deliveries`, `retry_delivery` | What an endpoint was sent and how each went; try one again now. |
|
|
422
|
+
| `suppressions.list`, `all` | The addresses not sent to, a page at a time or all of them. |
|
|
423
|
+
| `suppressions.add`, `lift`, `lift_all` | Block an address for a sending domain, or let it be sent to again. |
|
|
424
|
+
| `received.get`, `list`, `all`, `raw`, `file`, `delete` | The emails that came for your addresses, while the server keeps them. |
|
|
425
|
+
| `templates.create`, `list`, `get`, `update`, `delete` | Manage the templates emails are sent from. `name_taken` for a name its domain has. |
|
|
426
|
+
| `emails.file` | What one of an email's files held, where the server keeps it (`kept` says so). |
|
|
427
|
+
| `captured` | The emails a development server (capture driver) kept instead of sending; a `NotCapturingError` from a server that delivers for real. |
|
|
428
|
+
|
|
429
|
+
In a change (`webhooks.update`, `templates.update`) what is left out is left
|
|
430
|
+
as it is, and what is given is changed to exactly that: `enabled=False`
|
|
431
|
+
disables the endpoint, `events=[]` makes it hear about every type.
|
|
432
|
+
|
|
433
|
+
The `all` calls walk a whole list a page at a time, and raise the first
|
|
434
|
+
error they meet. A page of `list` or `deliveries` holds `data` and, when
|
|
435
|
+
more follow, `next`: pass it back as `after`.
|
|
436
|
+
|
|
437
|
+
An endpoint that fails every try for days is paused by the server:
|
|
438
|
+
`w.paused_at` is set, nothing is sent to it, and it is still owed everything
|
|
439
|
+
that happens. `admin.webhooks.resume(w.id)` resumes it, and what it is owed
|
|
440
|
+
is sent then; an `update` never does. `w.failing_since` says since when
|
|
441
|
+
every try has failed.
|
|
442
|
+
|
|
443
|
+
## The server itself
|
|
444
|
+
|
|
445
|
+
```python
|
|
446
|
+
h = client.health() # needs no key
|
|
447
|
+
print(h.ok, h.events, h.webhooks, h.pruning)
|
|
448
|
+
|
|
449
|
+
l = client.limits() # l.quota is None for a provider with no allowance
|
|
450
|
+
```
|
|
451
|
+
|
|
452
|
+
## Options
|
|
453
|
+
|
|
454
|
+
Keyword arguments of `CairnPost(base_url, api_key, ...)`:
|
|
455
|
+
|
|
456
|
+
| Option | Does |
|
|
457
|
+
|---|---|
|
|
458
|
+
| `timeout` | How long a call may take, in seconds (150 by default). Keep it above the server's send and batch timeouts. |
|
|
459
|
+
| `max_answer_bytes` | How much of an answer is read (64 MiB by default). A larger one is an error that says so. A refusal is not counted: 64 KiB of one are read, and a longer one is its status alone. |
|
|
460
|
+
| `user_agent` | Put your application's name before the client's in `User-Agent`. |
|
|
461
|
+
| `tls` | An `ssl.SSLContext`, to trust a server by other certificates than the system's. |
|
|
462
|
+
|
|
463
|
+
## Contributing
|
|
464
|
+
|
|
465
|
+
See [CONTRIBUTING.md](https://github.com/mettjs/cairnpost-python/blob/main/CONTRIBUTING.md).
|
|
466
|
+
|
|
467
|
+
## License
|
|
468
|
+
|
|
469
|
+
[MIT](https://github.com/mettjs/cairnpost-python/blob/main/LICENSE)
|