agdirlabs-email 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.
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .pytest_cache/
4
+ .mypy_cache/
5
+ .ruff_cache/
6
+ .venv/
7
+ build/
8
+ dist/
9
+ *.egg-info/
@@ -0,0 +1,19 @@
1
+ # Changelog — agdirlabs-email (Python)
2
+
3
+ All notable changes to this package are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the package uses [Semantic Versioning](https://semver.org).
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.1.0] — 2026-10-30
8
+
9
+ ### Added
10
+
11
+ - `AgdirEmail` (sync) and `AsyncAgdirEmail` (async) clients for the Agdir Email API, built on `httpx`.
12
+ - `emails`: `send`, `send_batch` (strict or permissive validation), `get`, `cancel`.
13
+ - `domains`: `create`, `get`, `list`, `list_all`, `verify`, `delete`.
14
+ - `webhooks`: `create`, `get`, `list`, `list_all`, `update`, `delete`, `rotate_secret`, and `deliveries` (`list`, `list_all`, `get`, `attempts`, `replay`).
15
+ - `verify_webhook` for signed webhook requests (Standard Webhooks), returning a typed `WebhookEvent`.
16
+ - `AgdirEmailError` with `code`, `status`, `message` and `retry_after`; `WebhookVerificationError`.
17
+ - Automatic retries for rate limits, server errors and network failures, with generated idempotency keys for sends.
18
+ - Django email backend `agdirlabs_email.django.EmailBackend` (`pip install "agdirlabs-email[django]"`).
19
+ - Type hints throughout (`py.typed`).
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Agdir AS
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.
@@ -0,0 +1,353 @@
1
+ Metadata-Version: 2.5
2
+ Name: agdirlabs-email
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for Agdir Email — programmatic SMTP for developers.
5
+ Project-URL: Homepage, https://agdir.email
6
+ Project-URL: Documentation, https://github.com/AgdirAS/agdirlabs-sdks/tree/main/python#readme
7
+ Project-URL: Repository, https://github.com/AgdirAS/agdirlabs-sdks
8
+ Project-URL: Issues, https://github.com/AgdirAS/agdirlabs-sdks/issues
9
+ Project-URL: Changelog, https://github.com/AgdirAS/agdirlabs-sdks/blob/main/python/CHANGELOG.md
10
+ Author: Agdir AS
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: agdir,django,email,email-api,smtp,transactional-email,webhooks
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Framework :: Django
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Topic :: Communications :: Email
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.9
28
+ Requires-Dist: httpx<1,>=0.25
29
+ Provides-Extra: django
30
+ Requires-Dist: django>=4.2; extra == 'django'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # agdirlabs-email
34
+
35
+ [![PyPI](https://img.shields.io/pypi/v/agdirlabs-email.svg)](https://pypi.org/project/agdirlabs-email/)
36
+ [![Python](https://img.shields.io/pypi/pyversions/agdirlabs-email.svg)](https://pypi.org/project/agdirlabs-email/)
37
+ [![CI](https://github.com/AgdirAS/agdirlabs-sdks/actions/workflows/python.yml/badge.svg)](https://github.com/AgdirAS/agdirlabs-sdks/actions/workflows/python.yml)
38
+
39
+ The official Python SDK for [Agdir Email](https://agdir.email) — programmatic SMTP for developers, hosted in the EU. Built by [Agdir Labs](https://agdirlabs.com) at [Agdir](https://agdir.no).
40
+
41
+ - Sync and async clients (`AgdirEmail`, `AsyncAgdirEmail`) with the same API
42
+ - Fully typed (`py.typed`): `TypedDict` inputs, frozen dataclass results
43
+ - One dependency ([httpx](https://www.python-httpx.org)); Python 3.9+
44
+ - Safe automatic retries with idempotency keys
45
+ - Cursor pagination with `for` / `async for`
46
+ - Webhook signature verification built in
47
+ - Optional Django email backend
48
+
49
+ ## Install
50
+
51
+ ```bash
52
+ pip install agdirlabs-email
53
+ # with the Django email backend
54
+ pip install "agdirlabs-email[django]"
55
+ ```
56
+
57
+ ## Quick start
58
+
59
+ Create an API key at [app.agdir.email](https://app.agdir.email) and verify a sending domain, then:
60
+
61
+ ```python
62
+ from agdirlabs_email import AgdirEmail
63
+
64
+ client = AgdirEmail(api_key="re_...") # or set AGDIR_EMAIL_API_KEY and call AgdirEmail()
65
+
66
+ result = client.emails.send(
67
+ {
68
+ "from": "Acme <hello@acme.com>",
69
+ "to": "user@example.com",
70
+ "subject": "Welcome to Acme",
71
+ "html": "<p>Thanks for signing up!</p>",
72
+ }
73
+ )
74
+ print(result.id)
75
+ ```
76
+
77
+ Async code uses `AsyncAgdirEmail` — every method is the same, awaited:
78
+
79
+ ```python
80
+ from agdirlabs_email import AsyncAgdirEmail
81
+
82
+ async with AsyncAgdirEmail() as client:
83
+ result = await client.emails.send({...})
84
+ ```
85
+
86
+ Clients hold a connection pool: create one and reuse it, and close it with `client.close()` /
87
+ `await client.aclose()` or a `with` / `async with` block.
88
+
89
+ ## Emails
90
+
91
+ Email parameters are plain dicts (typed as `SendEmailParams`) with the API's field names, so `from` works as a key:
92
+
93
+ ```python
94
+ from datetime import datetime, timedelta, timezone
95
+
96
+ # Plain text, several recipients, reply-to, tags, custom headers
97
+ client.emails.send(
98
+ {
99
+ "from": "Acme <billing@acme.com>",
100
+ "to": ["ana@example.com", "ben@example.com"],
101
+ "cc": "finance@acme.com",
102
+ "reply_to": "support@acme.com",
103
+ "subject": "Your invoice",
104
+ "text": "Invoice #1042 is ready in your dashboard.",
105
+ "tags": [{"name": "kind", "value": "invoice"}],
106
+ "headers": {"X-Entity-Ref-ID": "inv-1042"},
107
+ }
108
+ )
109
+
110
+ # Schedule for later (a timezone-aware datetime or an ISO 8601 string), then cancel if plans change
111
+ sent = client.emails.send({**email, "scheduled_at": datetime.now(timezone.utc) + timedelta(hours=1)})
112
+ client.emails.cancel(sent.id)
113
+
114
+ # Delivery status
115
+ email = client.emails.get(sent.id)
116
+ email.status # 'queued' | 'scheduled' | 'sent' | 'delivered' | 'bounced' | 'complained' | …
117
+ email.from_, email.to, email.created_at # datetimes are timezone-aware; cc/bcc/reply_to are always lists
118
+
119
+ # Up to 100 emails per request (MAX_BATCH_SIZE)
120
+ batch = client.emails.send_batch([email1, email2])
121
+ [r.id for r in batch.data]
122
+
123
+ # Accept the valid ones, report the rest
124
+ batch = client.emails.send_batch(emails, validation="permissive")
125
+ for error in batch.errors:
126
+ print(error.index, error.message)
127
+ ```
128
+
129
+ ## Domains
130
+
131
+ ```python
132
+ domain = client.domains.create({"name": "acme.com"})
133
+ for record in domain.records: # add these to your DNS
134
+ print(record.purpose, record.type, record.name, record.value)
135
+
136
+ client.domains.verify(domain.id) # check DNS now instead of waiting
137
+ client.domains.get(domain.id).status # 'pending' → 'verified'
138
+
139
+ for d in client.domains.list_all(): # fetches further pages as you iterate
140
+ print(d.name, d.status)
141
+
142
+ page = client.domains.list(limit=10) # or page by hand
143
+ next_page = client.domains.list(limit=10, after=page.next_cursor) if page.has_more else None
144
+
145
+ client.domains.delete(domain.id)
146
+ ```
147
+
148
+ With the async client, `list_all()` is an async iterator: `async for d in client.domains.list_all(): ...`.
149
+
150
+ ## Webhooks
151
+
152
+ ```python
153
+ webhook = client.webhooks.create(
154
+ {
155
+ "endpoint": "https://acme.com/webhooks/email",
156
+ "events": ["email.delivered", "email.bounced", "email.complained"],
157
+ }
158
+ )
159
+ webhook.signing_secret # 'whsec_…' — store it to verify incoming events
160
+
161
+ client.webhooks.update(webhook.id, {"status": "disabled"})
162
+ client.webhooks.rotate_secret(webhook.id)
163
+
164
+ # What was sent to your endpoint, and each HTTP attempt
165
+ deliveries = client.webhooks.deliveries.list(webhook.id).data
166
+ attempts = client.webhooks.deliveries.attempts(webhook.id, deliveries[0].id).data
167
+ client.webhooks.deliveries.replay(webhook.id, deliveries[0].id)
168
+ ```
169
+
170
+ ### Verifying incoming events
171
+
172
+ Every request to your endpoint is signed ([Standard Webhooks](https://www.standardwebhooks.com)). Verify it against
173
+ the **raw** body before trusting it — `verify_webhook` returns the parsed event or raises `WebhookVerificationError`:
174
+
175
+ ```python
176
+ import os
177
+ from agdirlabs_email import verify_webhook, WebhookVerificationError
178
+
179
+ SECRET = os.environ["AGDIR_EMAIL_WEBHOOK_SECRET"]
180
+
181
+ # Django
182
+ from django.http import HttpResponse, HttpResponseBadRequest
183
+ from django.views.decorators.csrf import csrf_exempt
184
+ from django.views.decorators.http import require_POST
185
+
186
+
187
+ @csrf_exempt
188
+ @require_POST
189
+ def email_webhook(request):
190
+ try:
191
+ event = verify_webhook(request.body, request.headers, SECRET)
192
+ except WebhookVerificationError:
193
+ return HttpResponseBadRequest()
194
+ if event.type == "email.bounced":
195
+ mark_bounced(event.data.to, event.data.bounce)
196
+ return HttpResponse(status=204)
197
+
198
+
199
+ # Flask
200
+ @app.post("/webhooks/email")
201
+ def email_webhook():
202
+ try:
203
+ event = verify_webhook(request.get_data(), request.headers, SECRET)
204
+ except WebhookVerificationError:
205
+ abort(400)
206
+ ...
207
+ return "", 204
208
+
209
+
210
+ # FastAPI
211
+ @app.post("/webhooks/email", status_code=204)
212
+ async def email_webhook(request: Request):
213
+ try:
214
+ event = verify_webhook(await request.body(), request.headers, SECRET)
215
+ except WebhookVerificationError:
216
+ raise HTTPException(400)
217
+ ...
218
+ ```
219
+
220
+ Messages older than 5 minutes are rejected (`tolerance_seconds=` to change). Failed deliveries are retried for about
221
+ 18 hours; use `event.data.email_id` to deduplicate.
222
+
223
+ ## Django
224
+
225
+ Send Django mail (`send_mail`, `EmailMessage`, `EmailMultiAlternatives`, password-reset emails, …) through Agdir Email:
226
+
227
+ ```python
228
+ # settings.py
229
+ EMAIL_BACKEND = "agdirlabs_email.django.EmailBackend"
230
+ AGDIR_EMAIL_API_KEY = os.environ["AGDIR_EMAIL_API_KEY"] # optional: falls back to the environment variable
231
+ DEFAULT_FROM_EMAIL = "Acme <hello@acme.com>"
232
+ # Optional: AGDIR_EMAIL_BASE_URL, AGDIR_EMAIL_MAX_RETRIES (default 2), AGDIR_EMAIL_TIMEOUT (seconds, default 30)
233
+ ```
234
+
235
+ ```python
236
+ from django.core.mail import EmailMultiAlternatives
237
+
238
+ message = EmailMultiAlternatives(
239
+ "Your invoice",
240
+ "Plain-text body",
241
+ to=["ana@example.com"],
242
+ cc=["finance@acme.com"],
243
+ reply_to=["support@acme.com"],
244
+ headers={"X-Entity-Ref-ID": "inv-1042"},
245
+ )
246
+ message.attach_alternative("<p>HTML body</p>", "text/html")
247
+ message.tags = [{"name": "kind", "value": "invoice"}] # optional API extras: tags, scheduled_at
248
+ message.send()
249
+ message.agdir_email_id # the API's email id
250
+ ```
251
+
252
+ `from`, `to`, `cc`, `bcc`, `reply_to`, `subject`, the body (plain, or HTML with `content_subtype = "html"`), a
253
+ `text/html` alternative and extra headers are mapped. Display-only `To`/`Cc` header overrides are ignored, and messages
254
+ with attachments raise `AttachmentsNotSupportedError` (the API doesn't accept attachments yet). API failures raise
255
+ `AgdirEmailError` unless `fail_silently=True`.
256
+
257
+ ## Errors
258
+
259
+ Every failed call raises an `AgdirEmailError`:
260
+
261
+ ```python
262
+ from agdirlabs_email import AgdirEmailError
263
+
264
+ try:
265
+ client.emails.send(email)
266
+ except AgdirEmailError as err:
267
+ err.code # 'validation_error' | 'daily_quota_exceeded' | 'rate_limit_exceeded' | 'network_error' | 'timeout' | …
268
+ err.status # HTTP status, 0 if no response was received
269
+ err.message # human-readable explanation
270
+ err.retry_after # seconds, when the API sent retry-after
271
+ ```
272
+
273
+ | `code` | Status | Meaning |
274
+ | --- | --- | --- |
275
+ | `missing_api_key` | 401 / 0 | No API key (also raised by the constructor) |
276
+ | `invalid_api_key` | 403 | Unknown or revoked key |
277
+ | `restricted_api_key` | 401 | A sending-only key used on a read endpoint |
278
+ | `validation_error` | 422 / 403 | Invalid input, unverified domain, paused team, domain limit |
279
+ | `not_found` | 404 | No such email, domain or webhook |
280
+ | `invalid_idempotent_request` / `concurrent_idempotent_requests` | 409 | Idempotency key reused with a different body / in flight |
281
+ | `daily_quota_exceeded` / `monthly_quota_exceeded` | 429 | Plan limit reached (not retried) |
282
+ | `rate_limit_exceeded` | 429 | Too many requests per second (retried automatically) |
283
+ | `internal_server_error` | 5xx | Server error |
284
+ | `network_error` / `timeout` | 0 | No response |
285
+
286
+ ## Retries and idempotency
287
+
288
+ Rate limits (`429 rate_limit_exceeded`), server errors (408/500/502/503/504) and network failures are retried up to
289
+ `max_retries` times (default 2) with exponential backoff, honouring `retry-after`. Requests that could have side
290
+ effects are only retried when that's safe: sends carry an idempotency key, so a retry can never deliver an email twice.
291
+ The SDK generates one per call, or pass your own to make sends safe across process restarts too:
292
+
293
+ ```python
294
+ client.emails.send(email, idempotency_key=f"welcome/{user.id}")
295
+ ```
296
+
297
+ Quota errors are never retried.
298
+
299
+ ## Configuration
300
+
301
+ ```python
302
+ AgdirEmail(
303
+ api_key="re_...", # default: AGDIR_EMAIL_API_KEY
304
+ base_url="https://api.agdir.email", # default: AGDIR_EMAIL_BASE_URL, else this
305
+ max_retries=2,
306
+ timeout=30.0, # seconds, per attempt
307
+ http_client=httpx.Client(proxy="http://proxy:8080"), # optional; you close it
308
+ )
309
+ ```
310
+
311
+ Empty environment variables count as unset. With `AsyncAgdirEmail`, pass an `httpx.AsyncClient`. Async calls are
312
+ cancelled the usual way (`asyncio.timeout`, task cancellation).
313
+
314
+ ## Development
315
+
316
+ ```bash
317
+ cd python
318
+ pip install -e . --group dev # pip ≥ 25.1
319
+ ruff check . && ruff format --check . && mypy && pytest
320
+ ```
321
+
322
+ Without a local Python, run the same in Docker:
323
+
324
+ ```bash
325
+ docker run --rm -v "$PWD":/src -w /src python:3.13-slim \
326
+ sh -c 'pip install -q -e . --group dev && ruff check . && mypy && pytest'
327
+ ```
328
+
329
+ `tests/test_live.py` runs against a real API only when `AGDIR_EMAIL_LIVE_BASE_URL` and `AGDIR_EMAIL_LIVE_API_KEY`
330
+ (and optionally `AGDIR_EMAIL_LIVE_FROM`, an address on a verified domain) are set. Never point it at production.
331
+
332
+ ## Releasing
333
+
334
+ Releases are published to PyPI from GitHub Actions with
335
+ [Trusted Publishing](https://docs.pypi.org/trusted-publishers/) — no API tokens are stored anywhere.
336
+
337
+ 1. Bump `__version__` in `src/agdirlabs_email/_version.py` and move **Unreleased** in `CHANGELOG.md` to the new version.
338
+ 2. Commit, then push a tag `python/v<version>` (e.g. `python/v0.1.0`). `.github/workflows/python-release.yml` checks
339
+ that the tag matches `__version__`, runs the tests, builds the sdist and wheel with `python -m build` and publishes.
340
+
341
+ One-time setup (maintainers): on [pypi.org](https://pypi.org/manage/account/publishing/) add a *pending* trusted
342
+ publisher for project `agdirlabs-email` — owner `AgdirAS`, repository `agdirlabs-sdks`, workflow
343
+ `python-release.yml`, environment `pypi` — and create a `pypi` environment in the GitHub repository settings
344
+ (optionally with required reviewers).
345
+
346
+ ## Contributing
347
+
348
+ Issues and pull requests are welcome — see [CONTRIBUTING.md](https://github.com/AgdirAS/agdirlabs-sdks/blob/main/CONTRIBUTING.md). Changes are listed in
349
+ [CHANGELOG.md](https://github.com/AgdirAS/agdirlabs-sdks/blob/main/python/CHANGELOG.md).
350
+
351
+ ## License
352
+
353
+ [MIT](https://github.com/AgdirAS/agdirlabs-sdks/blob/main/python/LICENSE) © [Agdir AS](https://agdir.no)