mittena 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.
mittena-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mittena
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.
mittena-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: mittena
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for the Mittena email API
5
+ License: MIT
6
+ Project-URL: Homepage, https://mittena.com
7
+ Project-URL: Documentation, https://mittena.com/docs/sdks/
8
+ Keywords: email,transactional-email,mittena,api
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Dynamic: license-file
16
+
17
+ # Mittena Python SDK
18
+
19
+ Official Python client for the [Mittena](https://mittena.com) email API. No dependencies, Python 3.8+.
20
+
21
+ ```bash
22
+ pip install mittena
23
+ ```
24
+
25
+ ## Send an email
26
+
27
+ ```python
28
+ from mittena import Mittena
29
+
30
+ client = Mittena() # reads MITTENA_API_KEY
31
+
32
+ email = client.emails.send({
33
+ "from": "Acme <hello@acme.com>",
34
+ "to": "ayse@example.com",
35
+ "subject": "Siparişiniz yolda",
36
+ "html": "<p>Merhaba Ayşe, siparişiniz kargoya verildi.</p>",
37
+ "reply_to": "destek@acme.com",
38
+ "tags": [{"name": "category", "value": "shipping"}],
39
+ })
40
+ print(email["id"])
41
+ ```
42
+
43
+ Top-level keys can be `snake_case` (`reply_to`, `scheduled_at`) or the API's `camelCase`. Responses are plain dicts in the API's shape.
44
+
45
+ ```python
46
+ from datetime import datetime, timedelta, timezone
47
+
48
+ client.emails.send({"from": "hello@acme.com", "to": "ali@example.com", "template": {"id": "tpl_...", "variables": {"name": "Ali"}}})
49
+ sent = client.emails.send({"from": "hello@acme.com", "to": "ali@example.com", "subject": "Reminder", "text": "...",
50
+ "scheduled_at": datetime.now(timezone.utc) + timedelta(hours=1)})
51
+ client.emails.cancel(sent["id"])
52
+
53
+ for e in client.emails.list_all(status="bounced", since=datetime(2026, 11, 1, tzinfo=timezone.utc)):
54
+ print(e["to"])
55
+ ```
56
+
57
+ ## Errors
58
+
59
+ ```python
60
+ from mittena import MittenaError
61
+
62
+ try:
63
+ client.emails.send(email)
64
+ except MittenaError as e:
65
+ e.status_code # 422
66
+ e.name # "validation_error"
67
+ e.message_en # "The `subject` field is required."
68
+ e.message_tr # "`subject` alanı zorunludur."
69
+ e.message_in("tr") # pick by the user's language
70
+ e.field_messages_tr # {"subject": "`subject` alanı zorunludur."}
71
+ ```
72
+
73
+ ## Retries and idempotency
74
+
75
+ Rate limits (`429 rate_limit_exceeded`), `5xx` and network errors are retried twice with backoff (`max_retries=`).
76
+ Every send carries an `Idempotency-Key`, so a retry never sends twice. Pass your own to stay safe across restarts:
77
+
78
+ ```python
79
+ client.emails.send(email, idempotency_key=f"order-{order.id}")
80
+ ```
81
+
82
+ ## Webhooks
83
+
84
+ ```python
85
+ from flask import Flask, request
86
+ from mittena import Webhooks, WebhookVerificationError
87
+
88
+ @app.post("/webhooks/mittena")
89
+ def mittena_webhook():
90
+ try:
91
+ event = Webhooks.verify(request.get_data(), request.headers.get("Mittena-Signature"), os.environ["MITTENA_WEBHOOK_SECRET"])
92
+ except WebhookVerificationError:
93
+ return "Invalid signature", 400
94
+ if event["type"] == "email.bounced":
95
+ ...
96
+ return "", 200
97
+ ```
98
+
99
+ ## Everything else
100
+
101
+ `emails`, `domains`, `api_keys`, `webhooks`, `suppressions`, `templates`, `lists` (+ `lists.contacts`, with `import_csv`) and
102
+ `broadcasts` follow the [API reference](https://mittena.com/docs/). List methods take filters as keyword arguments
103
+ (`from_` for `from`) and either `page=` (returns `total`) or the `after=` cursor.
@@ -0,0 +1,87 @@
1
+ # Mittena Python SDK
2
+
3
+ Official Python client for the [Mittena](https://mittena.com) email API. No dependencies, Python 3.8+.
4
+
5
+ ```bash
6
+ pip install mittena
7
+ ```
8
+
9
+ ## Send an email
10
+
11
+ ```python
12
+ from mittena import Mittena
13
+
14
+ client = Mittena() # reads MITTENA_API_KEY
15
+
16
+ email = client.emails.send({
17
+ "from": "Acme <hello@acme.com>",
18
+ "to": "ayse@example.com",
19
+ "subject": "Siparişiniz yolda",
20
+ "html": "<p>Merhaba Ayşe, siparişiniz kargoya verildi.</p>",
21
+ "reply_to": "destek@acme.com",
22
+ "tags": [{"name": "category", "value": "shipping"}],
23
+ })
24
+ print(email["id"])
25
+ ```
26
+
27
+ Top-level keys can be `snake_case` (`reply_to`, `scheduled_at`) or the API's `camelCase`. Responses are plain dicts in the API's shape.
28
+
29
+ ```python
30
+ from datetime import datetime, timedelta, timezone
31
+
32
+ client.emails.send({"from": "hello@acme.com", "to": "ali@example.com", "template": {"id": "tpl_...", "variables": {"name": "Ali"}}})
33
+ sent = client.emails.send({"from": "hello@acme.com", "to": "ali@example.com", "subject": "Reminder", "text": "...",
34
+ "scheduled_at": datetime.now(timezone.utc) + timedelta(hours=1)})
35
+ client.emails.cancel(sent["id"])
36
+
37
+ for e in client.emails.list_all(status="bounced", since=datetime(2026, 11, 1, tzinfo=timezone.utc)):
38
+ print(e["to"])
39
+ ```
40
+
41
+ ## Errors
42
+
43
+ ```python
44
+ from mittena import MittenaError
45
+
46
+ try:
47
+ client.emails.send(email)
48
+ except MittenaError as e:
49
+ e.status_code # 422
50
+ e.name # "validation_error"
51
+ e.message_en # "The `subject` field is required."
52
+ e.message_tr # "`subject` alanı zorunludur."
53
+ e.message_in("tr") # pick by the user's language
54
+ e.field_messages_tr # {"subject": "`subject` alanı zorunludur."}
55
+ ```
56
+
57
+ ## Retries and idempotency
58
+
59
+ Rate limits (`429 rate_limit_exceeded`), `5xx` and network errors are retried twice with backoff (`max_retries=`).
60
+ Every send carries an `Idempotency-Key`, so a retry never sends twice. Pass your own to stay safe across restarts:
61
+
62
+ ```python
63
+ client.emails.send(email, idempotency_key=f"order-{order.id}")
64
+ ```
65
+
66
+ ## Webhooks
67
+
68
+ ```python
69
+ from flask import Flask, request
70
+ from mittena import Webhooks, WebhookVerificationError
71
+
72
+ @app.post("/webhooks/mittena")
73
+ def mittena_webhook():
74
+ try:
75
+ event = Webhooks.verify(request.get_data(), request.headers.get("Mittena-Signature"), os.environ["MITTENA_WEBHOOK_SECRET"])
76
+ except WebhookVerificationError:
77
+ return "Invalid signature", 400
78
+ if event["type"] == "email.bounced":
79
+ ...
80
+ return "", 200
81
+ ```
82
+
83
+ ## Everything else
84
+
85
+ `emails`, `domains`, `api_keys`, `webhooks`, `suppressions`, `templates`, `lists` (+ `lists.contacts`, with `import_csv`) and
86
+ `broadcasts` follow the [API reference](https://mittena.com/docs/). List methods take filters as keyword arguments
87
+ (`from_` for `from`) and either `page=` (returns `total`) or the `after=` cursor.
@@ -0,0 +1,7 @@
1
+ """Official Python SDK for the Mittena email API. https://mittena.com/docs/sdks/"""
2
+
3
+ from ._client import Mittena, VERSION as __version__
4
+ from ._errors import MittenaError
5
+ from ._webhooks import Webhooks, WebhookVerificationError
6
+
7
+ __all__ = ["Mittena", "MittenaError", "Webhooks", "WebhookVerificationError", "__version__"]
@@ -0,0 +1,349 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import random
6
+ import time
7
+ import uuid
8
+ from datetime import date, datetime, timezone
9
+ from typing import Any, Dict, Iterator, List, Mapping, Optional
10
+ from urllib import error as urlerror
11
+ from urllib import parse, request
12
+
13
+ from ._errors import MittenaError
14
+ from ._webhooks import Webhooks
15
+
16
+ VERSION = "0.1.0"
17
+
18
+ Json = Dict[str, Any]
19
+
20
+
21
+ def _camel(key: str) -> str:
22
+ """reply_to -> replyTo; `from_` -> from. camelCase keys pass through."""
23
+ key = key.rstrip("_")
24
+ head, *rest = key.split("_")
25
+ return head + "".join(p[:1].upper() + p[1:] for p in rest)
26
+
27
+
28
+ def _encode(value: Any) -> Any:
29
+ if isinstance(value, datetime):
30
+ if value.tzinfo is None:
31
+ raise ValueError("Use a timezone-aware datetime (e.g. datetime.now(timezone.utc)).")
32
+ return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
33
+ if isinstance(value, date):
34
+ return value.isoformat()
35
+ if isinstance(value, Mapping):
36
+ return {k: _encode(v) for k, v in value.items()}
37
+ if isinstance(value, (list, tuple)):
38
+ return [_encode(v) for v in value]
39
+ return value
40
+
41
+
42
+ def _params(params: Optional[Mapping[str, Any]], camel_keys: bool = True) -> Json:
43
+ """Top-level keys may be snake_case; nested values (headers, variables, fields) are left as given."""
44
+ if not params:
45
+ return {}
46
+ return {(_camel(k) if camel_keys else k): _encode(v) for k, v in params.items() if v is not None}
47
+
48
+
49
+ class Mittena:
50
+ """Client for https://api.mittena.com.
51
+
52
+ >>> client = Mittena("mt_live_...")
53
+ >>> client.emails.send({"from": "Acme <hello@acme.com>", "to": "user@example.com", "subject": "Hi", "html": "<p>Hi</p>"})
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ api_key: Optional[str] = None,
59
+ *,
60
+ base_url: str = "https://api.mittena.com",
61
+ max_retries: int = 2,
62
+ timeout: float = 30.0,
63
+ ) -> None:
64
+ key = api_key or os.environ.get("MITTENA_API_KEY")
65
+ if not key:
66
+ raise ValueError('Missing API key. Pass it to Mittena("mt_live_...") or set MITTENA_API_KEY.')
67
+ self._api_key = key
68
+ self._base_url = base_url.rstrip("/")
69
+ self._max_retries = max_retries
70
+ self._timeout = timeout
71
+ self.emails = Emails(self)
72
+ self.domains = Domains(self)
73
+ self.api_keys = ApiKeys(self)
74
+ self.webhooks = WebhooksApi(self)
75
+ self.suppressions = Suppressions(self)
76
+ self.templates = Templates(self)
77
+ self.lists = Lists(self)
78
+ self.broadcasts = Broadcasts(self)
79
+
80
+ def request(
81
+ self,
82
+ method: str,
83
+ path: str,
84
+ query: Optional[Mapping[str, Any]] = None,
85
+ body: Any = None,
86
+ idempotency_key: Optional[str] = None,
87
+ ) -> Any:
88
+ url = self._base_url + path
89
+ q = {k: v for k, v in _params(query).items() if v != ""}
90
+ if q:
91
+ url += "?" + parse.urlencode({k: str(v).lower() if isinstance(v, bool) else v for k, v in q.items()})
92
+ headers = {
93
+ "Authorization": f"Bearer {self._api_key}",
94
+ "Accept": "application/json",
95
+ "User-Agent": f"mittena-python/{VERSION}",
96
+ }
97
+ data = None
98
+ if body is not None:
99
+ data = json.dumps(body).encode("utf-8")
100
+ headers["Content-Type"] = "application/json"
101
+ # A send is retried only with a key, so a retry can never send twice.
102
+ if idempotency_key is None and method == "POST" and path.startswith("/v1/emails") and not path.endswith("/cancel"):
103
+ idempotency_key = str(uuid.uuid4())
104
+ if idempotency_key:
105
+ headers["Idempotency-Key"] = idempotency_key
106
+
107
+ attempt = 0
108
+ while True:
109
+ req = request.Request(url, data=data, method=method, headers=headers)
110
+ try:
111
+ with request.urlopen(req, timeout=self._timeout) as res:
112
+ text = res.read().decode("utf-8")
113
+ return json.loads(text) if text else None
114
+ except urlerror.HTTPError as e:
115
+ text = e.read().decode("utf-8", errors="replace")
116
+ try:
117
+ payload = json.loads(text) if text else None
118
+ except ValueError:
119
+ payload = None
120
+ err = MittenaError.from_response(e.code, payload, text)
121
+ retryable = e.code >= 500 or (e.code == 429 and err.name == "rate_limit_exceeded")
122
+ if not retryable or attempt >= self._max_retries:
123
+ raise err from None
124
+ retry_after = e.headers.get("Retry-After") if e.headers else None
125
+ wait = float(retry_after) if retry_after and retry_after.isdigit() and int(retry_after) > 0 else _backoff(attempt)
126
+ except (urlerror.URLError, TimeoutError, ConnectionError) as e:
127
+ if attempt >= self._max_retries:
128
+ raise MittenaError(0, "network_error", f"Request failed: {e}") from None
129
+ wait = _backoff(attempt)
130
+ time.sleep(wait)
131
+ attempt += 1
132
+
133
+
134
+ def _backoff(attempt: int) -> float:
135
+ return min(8.0, 0.5 * 2**attempt) * random.uniform(0.75, 1.25)
136
+
137
+
138
+ def _q(value: str) -> str:
139
+ return parse.quote(value, safe="")
140
+
141
+
142
+ class _Resource:
143
+ def __init__(self, client: Mittena) -> None:
144
+ self._client = client
145
+
146
+ def _get(self, path: str, query: Optional[Mapping[str, Any]] = None) -> Any:
147
+ return self._client.request("GET", path, query=query)
148
+
149
+ def _post(self, path: str, body: Any = None, idempotency_key: Optional[str] = None) -> Any:
150
+ return self._client.request("POST", path, body=body, idempotency_key=idempotency_key)
151
+
152
+ def _patch(self, path: str, body: Any) -> Any:
153
+ return self._client.request("PATCH", path, body=body)
154
+
155
+ def _delete(self, path: str) -> Any:
156
+ return self._client.request("DELETE", path)
157
+
158
+
159
+ class Emails(_Resource):
160
+ def send(self, params: Mapping[str, Any], *, idempotency_key: Optional[str] = None) -> Json:
161
+ """POST /v1/emails. Keys: from, to, cc, bcc, reply_to, subject, html, text, headers, tags, scheduled_at, template, unsubscribe."""
162
+ return self._post("/v1/emails", _params(params), idempotency_key)
163
+
164
+ def send_batch(self, emails: List[Mapping[str, Any]], *, idempotency_key: Optional[str] = None) -> Json:
165
+ """POST /v1/emails/batch (up to 100 emails, one rate-limit hit)."""
166
+ return self._post("/v1/emails/batch", [_params(e) for e in emails], idempotency_key)
167
+
168
+ def get(self, email_id: str) -> Json:
169
+ return self._get(f"/v1/emails/{_q(email_id)}")
170
+
171
+ def list(self, **params: Any) -> Json:
172
+ """Filters: status, to, from_, tag, q, since, until, limit, after (cursor) or page."""
173
+ return self._get("/v1/emails", params)
174
+
175
+ def list_all(self, **params: Any) -> Iterator[Json]:
176
+ """Walks every page with the cursor."""
177
+ params.pop("page", None)
178
+ after: Optional[str] = None
179
+ while True:
180
+ page = self.list(**params, after=after)
181
+ yield from page["data"]
182
+ if not page.get("hasMore") or not page["data"]:
183
+ return
184
+ after = page["data"][-1]["id"]
185
+
186
+ def cancel(self, email_id: str) -> Json:
187
+ """Cancels a scheduled email that has not been sent yet."""
188
+ return self._post(f"/v1/emails/{_q(email_id)}/cancel")
189
+
190
+
191
+ class Domains(_Resource):
192
+ def create(self, name: str, region: Optional[str] = None) -> Json:
193
+ return self._post("/v1/domains", _params({"name": name, "region": region}))
194
+
195
+ def list(self, **params: Any) -> Json:
196
+ return self._get("/v1/domains", params)
197
+
198
+ def get(self, domain_id: str) -> Json:
199
+ return self._get(f"/v1/domains/{_q(domain_id)}")
200
+
201
+ def verify(self, domain_id: str) -> Json:
202
+ """Checks the DNS records now."""
203
+ return self._post(f"/v1/domains/{_q(domain_id)}/verify")
204
+
205
+ def remove(self, domain_id: str) -> Any:
206
+ return self._delete(f"/v1/domains/{_q(domain_id)}")
207
+
208
+
209
+ class ApiKeys(_Resource):
210
+ def create(self, name: str, permission: str = "full_access", domain_id: Optional[str] = None) -> Json:
211
+ """Returns {id, token}; the token is shown only here."""
212
+ return self._post("/v1/api-keys", _params({"name": name, "permission": permission, "domain_id": domain_id}))
213
+
214
+ def list(self, **params: Any) -> Json:
215
+ return self._get("/v1/api-keys", params)
216
+
217
+ def remove(self, key_id: str) -> Any:
218
+ return self._delete(f"/v1/api-keys/{_q(key_id)}")
219
+
220
+
221
+ class WebhooksApi(_Resource):
222
+ verify = staticmethod(Webhooks.verify)
223
+
224
+ def create(self, url: str, events: List[str]) -> Json:
225
+ """The response holds signingSecret, shown only here."""
226
+ return self._post("/v1/webhooks", {"url": url, "events": events})
227
+
228
+ def list(self, **params: Any) -> Json:
229
+ return self._get("/v1/webhooks", params)
230
+
231
+ def get(self, webhook_id: str) -> Json:
232
+ return self._get(f"/v1/webhooks/{_q(webhook_id)}")
233
+
234
+ def update(self, webhook_id: str, **params: Any) -> Json:
235
+ return self._patch(f"/v1/webhooks/{_q(webhook_id)}", _params(params))
236
+
237
+ def remove(self, webhook_id: str) -> Any:
238
+ return self._delete(f"/v1/webhooks/{_q(webhook_id)}")
239
+
240
+ def deliveries(self, webhook_id: str, **params: Any) -> Json:
241
+ return self._get(f"/v1/webhooks/{_q(webhook_id)}/deliveries", params)
242
+
243
+
244
+ class Suppressions(_Resource):
245
+ def list(self, **params: Any) -> Json:
246
+ return self._get("/v1/suppressions", params)
247
+
248
+ def add(self, email: str) -> Json:
249
+ return self._post("/v1/suppressions", {"email": email})
250
+
251
+ def remove(self, email: str) -> Any:
252
+ return self._delete(f"/v1/suppressions/{_q(email)}")
253
+
254
+
255
+ class Templates(_Resource):
256
+ def create(self, params: Mapping[str, Any]) -> Json:
257
+ """Keys: name, alias, subject, html, text, variables ([{key, fallback}])."""
258
+ return self._post("/v1/templates", _params(params))
259
+
260
+ def list(self, **params: Any) -> Json:
261
+ return self._get("/v1/templates", params)
262
+
263
+ def get(self, template_id: str) -> Json:
264
+ return self._get(f"/v1/templates/{_q(template_id)}")
265
+
266
+ def update(self, template_id: str, params: Mapping[str, Any]) -> Json:
267
+ return self._patch(f"/v1/templates/{_q(template_id)}", _params(params))
268
+
269
+ def publish(self, template_id: str) -> Json:
270
+ """Makes the current draft the version that sends use."""
271
+ return self._post(f"/v1/templates/{_q(template_id)}/publish")
272
+
273
+ def duplicate(self, template_id: str) -> Json:
274
+ return self._post(f"/v1/templates/{_q(template_id)}/duplicate")
275
+
276
+ def remove(self, template_id: str) -> Any:
277
+ return self._delete(f"/v1/templates/{_q(template_id)}")
278
+
279
+
280
+ class Contacts(_Resource):
281
+ def list(self, list_id: str, **params: Any) -> Json:
282
+ return self._get(f"/v1/lists/{_q(list_id)}/contacts", params)
283
+
284
+ def upsert(self, list_id: str, params: Mapping[str, Any]) -> Json:
285
+ """Adds a contact, or updates it when the email is already on the list. Keys: email, first_name, last_name, fields."""
286
+ return self._post(f"/v1/lists/{_q(list_id)}/contacts", _params(params))
287
+
288
+ def update(self, list_id: str, contact_id: str, params: Mapping[str, Any]) -> Json:
289
+ return self._patch(f"/v1/lists/{_q(list_id)}/contacts/{_q(contact_id)}", _params(params))
290
+
291
+ def remove(self, list_id: str, contact_id: str) -> Any:
292
+ return self._delete(f"/v1/lists/{_q(list_id)}/contacts/{_q(contact_id)}")
293
+
294
+ def import_csv(self, list_id: str, csv: str) -> Json:
295
+ """CSV with an `email` column; other columns become fields."""
296
+ return self._post(f"/v1/lists/{_q(list_id)}/contacts/import", {"csv": csv})
297
+
298
+
299
+ class Lists(_Resource):
300
+ def __init__(self, client: Mittena) -> None:
301
+ super().__init__(client)
302
+ self.contacts = Contacts(client)
303
+
304
+ def create(self, name: str) -> Json:
305
+ return self._post("/v1/lists", {"name": name})
306
+
307
+ def list(self, **params: Any) -> Json:
308
+ return self._get("/v1/lists", params)
309
+
310
+ def get(self, list_id: str) -> Json:
311
+ return self._get(f"/v1/lists/{_q(list_id)}")
312
+
313
+ def update(self, list_id: str, name: str) -> Json:
314
+ return self._patch(f"/v1/lists/{_q(list_id)}", {"name": name})
315
+
316
+ def remove(self, list_id: str) -> Any:
317
+ return self._delete(f"/v1/lists/{_q(list_id)}")
318
+
319
+
320
+ class Broadcasts(_Resource):
321
+ def create(self, params: Mapping[str, Any]) -> Json:
322
+ """Keys: name, list_id, from, reply_to, subject, html, text."""
323
+ return self._post("/v1/broadcasts", _params(params))
324
+
325
+ def list(self, **params: Any) -> Json:
326
+ return self._get("/v1/broadcasts", params)
327
+
328
+ def get(self, broadcast_id: str) -> Json:
329
+ return self._get(f"/v1/broadcasts/{_q(broadcast_id)}")
330
+
331
+ def update(self, broadcast_id: str, params: Mapping[str, Any]) -> Json:
332
+ return self._patch(f"/v1/broadcasts/{_q(broadcast_id)}", _params(params))
333
+
334
+ def remove(self, broadcast_id: str) -> Any:
335
+ return self._delete(f"/v1/broadcasts/{_q(broadcast_id)}")
336
+
337
+ def duplicate(self, broadcast_id: str) -> Json:
338
+ return self._post(f"/v1/broadcasts/{_q(broadcast_id)}/duplicate")
339
+
340
+ def send(self, broadcast_id: str, scheduled_at: Optional[datetime] = None) -> Json:
341
+ """Sends now, or at scheduled_at. Also resumes a paused broadcast."""
342
+ return self._post(f"/v1/broadcasts/{_q(broadcast_id)}/send", _params({"scheduled_at": scheduled_at}))
343
+
344
+ def cancel(self, broadcast_id: str) -> Json:
345
+ return self._post(f"/v1/broadcasts/{_q(broadcast_id)}/cancel")
346
+
347
+ def test(self, broadcast_id: str, to: List[str]) -> Any:
348
+ """Sends a test copy to up to 5 addresses."""
349
+ return self._post(f"/v1/broadcasts/{_q(broadcast_id)}/test", {"to": to})
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Dict, List, Optional
4
+
5
+
6
+ class MittenaError(Exception):
7
+ """Any non-2xx response.
8
+
9
+ ``name`` is the stable error code to branch on (validation_error, not_found, rate_limit_exceeded, ...).
10
+ ``message_en`` / ``message_tr`` hold the same message in English and Turkish.
11
+ """
12
+
13
+ def __init__(
14
+ self,
15
+ status_code: int,
16
+ name: str,
17
+ message: str,
18
+ message_en: Optional[str] = None,
19
+ message_tr: Optional[str] = None,
20
+ errors: Optional[Dict[str, List[str]]] = None,
21
+ field_messages_en: Optional[Dict[str, str]] = None,
22
+ field_messages_tr: Optional[Dict[str, str]] = None,
23
+ ) -> None:
24
+ super().__init__(message)
25
+ self.status_code = status_code
26
+ self.name = name
27
+ self.message = message
28
+ self.message_en = message_en or message
29
+ self.message_tr = message_tr or message
30
+ self.errors = errors or {}
31
+ self.field_messages_en = field_messages_en or {}
32
+ self.field_messages_tr = field_messages_tr or {}
33
+
34
+ def message_in(self, lang: str) -> str:
35
+ """The message in the given language ("tr" or "en")."""
36
+ return self.message_tr if lang.lower().startswith("tr") else self.message_en
37
+
38
+ def __str__(self) -> str:
39
+ return f"{self.name}: {self.message}"
40
+
41
+ def __repr__(self) -> str:
42
+ return f"MittenaError(status_code={self.status_code}, name={self.name!r}, message={self.message!r})"
43
+
44
+ @classmethod
45
+ def from_response(cls, status: int, body: Any, text: str) -> "MittenaError":
46
+ if isinstance(body, dict) and isinstance(body.get("name"), str) and isinstance(body.get("message"), str):
47
+ return cls(
48
+ status_code=body.get("statusCode") or status,
49
+ name=body["name"],
50
+ message=body["message"],
51
+ message_en=body.get("messageEn"),
52
+ message_tr=body.get("messageTr"),
53
+ errors=body.get("errors"),
54
+ field_messages_en=body.get("fieldMessagesEn"),
55
+ field_messages_tr=body.get("fieldMessagesTr"),
56
+ )
57
+ return cls(status, "http_error", f"HTTP {status}: {text[:200]}")
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import hmac
5
+ import json
6
+ import time
7
+ from typing import Any, Dict, Optional, Union
8
+
9
+
10
+ class WebhookVerificationError(Exception):
11
+ pass
12
+
13
+
14
+ class Webhooks:
15
+ @staticmethod
16
+ def verify(
17
+ raw_body: Union[str, bytes],
18
+ signature_header: Optional[str],
19
+ secret: str,
20
+ tolerance_seconds: int = 300,
21
+ now: Optional[float] = None,
22
+ ) -> Dict[str, Any]:
23
+ """Checks the ``Mittena-Signature`` header (``t=<unix>,v1=<hex hmac>``) against the raw body and returns the event.
24
+
25
+ Pass the body exactly as received (``request.get_data()`` in Flask, ``await request.body()`` in FastAPI).
26
+ Raises WebhookVerificationError when it does not match.
27
+ """
28
+ if not secret:
29
+ raise WebhookVerificationError("Missing signing secret.")
30
+ parts: Dict[str, str] = {}
31
+ for piece in (signature_header or "").split(","):
32
+ key, sep, value = piece.partition("=")
33
+ if sep:
34
+ parts[key.strip()] = value.strip()
35
+ try:
36
+ timestamp = int(parts["t"])
37
+ given = parts["v1"]
38
+ except (KeyError, ValueError):
39
+ raise WebhookVerificationError("Missing or malformed Mittena-Signature header.") from None
40
+ if abs((now if now is not None else time.time()) - timestamp) > tolerance_seconds:
41
+ raise WebhookVerificationError("Timestamp is outside the tolerance.")
42
+
43
+ body = raw_body.decode("utf-8") if isinstance(raw_body, bytes) else raw_body
44
+ expected = hmac.new(secret.encode(), f"{parts['t']}.{body}".encode(), hashlib.sha256).hexdigest()
45
+ if not hmac.compare_digest(expected, given.lower()):
46
+ raise WebhookVerificationError("Signature does not match.")
47
+ return json.loads(body)
48
+
49
+ @staticmethod
50
+ def sign(raw_body: str, secret: str, timestamp: Optional[int] = None) -> str:
51
+ """Builds a header value; useful to test your handler."""
52
+ t = int(time.time()) if timestamp is None else timestamp
53
+ digest = hmac.new(secret.encode(), f"{t}.{raw_body}".encode(), hashlib.sha256).hexdigest()
54
+ return f"t={t},v1={digest}"
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: mittena
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for the Mittena email API
5
+ License: MIT
6
+ Project-URL: Homepage, https://mittena.com
7
+ Project-URL: Documentation, https://mittena.com/docs/sdks/
8
+ Keywords: email,transactional-email,mittena,api
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Dynamic: license-file
16
+
17
+ # Mittena Python SDK
18
+
19
+ Official Python client for the [Mittena](https://mittena.com) email API. No dependencies, Python 3.8+.
20
+
21
+ ```bash
22
+ pip install mittena
23
+ ```
24
+
25
+ ## Send an email
26
+
27
+ ```python
28
+ from mittena import Mittena
29
+
30
+ client = Mittena() # reads MITTENA_API_KEY
31
+
32
+ email = client.emails.send({
33
+ "from": "Acme <hello@acme.com>",
34
+ "to": "ayse@example.com",
35
+ "subject": "Siparişiniz yolda",
36
+ "html": "<p>Merhaba Ayşe, siparişiniz kargoya verildi.</p>",
37
+ "reply_to": "destek@acme.com",
38
+ "tags": [{"name": "category", "value": "shipping"}],
39
+ })
40
+ print(email["id"])
41
+ ```
42
+
43
+ Top-level keys can be `snake_case` (`reply_to`, `scheduled_at`) or the API's `camelCase`. Responses are plain dicts in the API's shape.
44
+
45
+ ```python
46
+ from datetime import datetime, timedelta, timezone
47
+
48
+ client.emails.send({"from": "hello@acme.com", "to": "ali@example.com", "template": {"id": "tpl_...", "variables": {"name": "Ali"}}})
49
+ sent = client.emails.send({"from": "hello@acme.com", "to": "ali@example.com", "subject": "Reminder", "text": "...",
50
+ "scheduled_at": datetime.now(timezone.utc) + timedelta(hours=1)})
51
+ client.emails.cancel(sent["id"])
52
+
53
+ for e in client.emails.list_all(status="bounced", since=datetime(2026, 11, 1, tzinfo=timezone.utc)):
54
+ print(e["to"])
55
+ ```
56
+
57
+ ## Errors
58
+
59
+ ```python
60
+ from mittena import MittenaError
61
+
62
+ try:
63
+ client.emails.send(email)
64
+ except MittenaError as e:
65
+ e.status_code # 422
66
+ e.name # "validation_error"
67
+ e.message_en # "The `subject` field is required."
68
+ e.message_tr # "`subject` alanı zorunludur."
69
+ e.message_in("tr") # pick by the user's language
70
+ e.field_messages_tr # {"subject": "`subject` alanı zorunludur."}
71
+ ```
72
+
73
+ ## Retries and idempotency
74
+
75
+ Rate limits (`429 rate_limit_exceeded`), `5xx` and network errors are retried twice with backoff (`max_retries=`).
76
+ Every send carries an `Idempotency-Key`, so a retry never sends twice. Pass your own to stay safe across restarts:
77
+
78
+ ```python
79
+ client.emails.send(email, idempotency_key=f"order-{order.id}")
80
+ ```
81
+
82
+ ## Webhooks
83
+
84
+ ```python
85
+ from flask import Flask, request
86
+ from mittena import Webhooks, WebhookVerificationError
87
+
88
+ @app.post("/webhooks/mittena")
89
+ def mittena_webhook():
90
+ try:
91
+ event = Webhooks.verify(request.get_data(), request.headers.get("Mittena-Signature"), os.environ["MITTENA_WEBHOOK_SECRET"])
92
+ except WebhookVerificationError:
93
+ return "Invalid signature", 400
94
+ if event["type"] == "email.bounced":
95
+ ...
96
+ return "", 200
97
+ ```
98
+
99
+ ## Everything else
100
+
101
+ `emails`, `domains`, `api_keys`, `webhooks`, `suppressions`, `templates`, `lists` (+ `lists.contacts`, with `import_csv`) and
102
+ `broadcasts` follow the [API reference](https://mittena.com/docs/). List methods take filters as keyword arguments
103
+ (`from_` for `from`) and either `page=` (returns `total`) or the `after=` cursor.
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ mittena/__init__.py
5
+ mittena/_client.py
6
+ mittena/_errors.py
7
+ mittena/_webhooks.py
8
+ mittena.egg-info/PKG-INFO
9
+ mittena.egg-info/SOURCES.txt
10
+ mittena.egg-info/dependency_links.txt
11
+ mittena.egg-info/top_level.txt
12
+ tests/test_client.py
@@ -0,0 +1 @@
1
+ mittena
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mittena"
7
+ version = "0.1.0"
8
+ description = "Official Python SDK for the Mittena email API"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.8"
12
+ dependencies = []
13
+ keywords = ["email", "transactional-email", "mittena", "api"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://mittena.com"
22
+ Documentation = "https://mittena.com/docs/sdks/"
23
+
24
+ [tool.setuptools]
25
+ packages = ["mittena"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,150 @@
1
+ import json
2
+ import threading
3
+ import time
4
+ import unittest
5
+ from datetime import datetime, timezone
6
+ from http.server import BaseHTTPRequestHandler, HTTPServer
7
+
8
+ from mittena import Mittena, MittenaError, Webhooks, WebhookVerificationError
9
+
10
+
11
+ class FakeApi:
12
+ """Answers with queued responses in order and records the requests."""
13
+
14
+ def __init__(self, responses):
15
+ self.responses = list(responses)
16
+ self.requests = []
17
+ api = self
18
+
19
+ class Handler(BaseHTTPRequestHandler):
20
+ def log_message(self, *args):
21
+ pass
22
+
23
+ def _handle(self):
24
+ length = int(self.headers.get("Content-Length") or 0)
25
+ raw = self.rfile.read(length).decode() if length else ""
26
+ api.requests.append({"method": self.command, "path": self.path, "headers": dict(self.headers),
27
+ "body": json.loads(raw) if raw else None})
28
+ status, body, headers = api.responses.pop(0) if api.responses else (500, {}, {})
29
+ data = json.dumps(body).encode()
30
+ self.send_response(status)
31
+ self.send_header("Content-Type", "application/json")
32
+ self.send_header("Content-Length", str(len(data)))
33
+ for k, v in (headers or {}).items():
34
+ self.send_header(k, v)
35
+ self.end_headers()
36
+ self.wfile.write(data)
37
+
38
+ do_GET = do_POST = do_PATCH = do_DELETE = _handle
39
+
40
+ self.server = HTTPServer(("127.0.0.1", 0), Handler)
41
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
42
+ self.base_url = f"http://127.0.0.1:{self.server.server_port}"
43
+
44
+ def close(self):
45
+ self.server.shutdown()
46
+
47
+
48
+ class ClientTests(unittest.TestCase):
49
+ def test_send_uses_camel_case_auth_and_idempotency(self):
50
+ api = FakeApi([(200, {"id": "em_1"}, None)])
51
+ client = Mittena("mt_test", base_url=api.base_url)
52
+ res = client.emails.send({"from": "a@acme.com", "to": "b@example.com", "reply_to": "r@acme.com", "html": "<p>x</p>",
53
+ "headers": {"X-Order_Id": "42"},
54
+ "scheduled_at": datetime(2030, 1, 1, tzinfo=timezone.utc)})
55
+ api.close()
56
+ self.assertEqual(res["id"], "em_1")
57
+ r = api.requests[0]
58
+ self.assertEqual((r["method"], r["path"]), ("POST", "/v1/emails"))
59
+ self.assertEqual(r["headers"]["Authorization"], "Bearer mt_test")
60
+ self.assertTrue(r["headers"]["User-Agent"].startswith("mittena-python/"))
61
+ self.assertTrue(r["headers"]["Idempotency-Key"])
62
+ self.assertEqual(r["body"]["replyTo"], "r@acme.com")
63
+ self.assertEqual(r["body"]["headers"], {"X-Order_Id": "42"})
64
+ self.assertEqual(r["body"]["scheduledAt"], "2030-01-01T00:00:00Z")
65
+
66
+ def test_rate_limit_is_retried_with_same_key(self):
67
+ api = FakeApi([
68
+ (429, {"statusCode": 429, "name": "rate_limit_exceeded", "message": "Too many requests."}, {"Retry-After": "0"}),
69
+ (200, {"id": "em_2"}, None),
70
+ ])
71
+ client = Mittena("k", base_url=api.base_url)
72
+ res = client.emails.send({"from": "a@acme.com", "to": "b@example.com", "text": "x"}, idempotency_key="order-42")
73
+ api.close()
74
+ self.assertEqual(res["id"], "em_2")
75
+ self.assertEqual([r["headers"]["Idempotency-Key"] for r in api.requests], ["order-42", "order-42"])
76
+
77
+ def test_quota_error_not_retried_and_bilingual(self):
78
+ api = FakeApi([(429, {"statusCode": 429, "name": "daily_quota_exceeded", "message": "Daily quota of 100 emails reached.",
79
+ "messageEn": "Daily quota of 100 emails reached.", "messageTr": "Günlük 100 e-posta kotası doldu."}, None)])
80
+ client = Mittena("k", base_url=api.base_url)
81
+ with self.assertRaises(MittenaError) as ctx:
82
+ client.emails.send({"from": "a@acme.com", "to": "b@example.com", "text": "x"})
83
+ api.close()
84
+ err = ctx.exception
85
+ self.assertEqual((err.status_code, err.name), (429, "daily_quota_exceeded"))
86
+ self.assertEqual(err.message_in("tr-TR"), "Günlük 100 e-posta kotası doldu.")
87
+ self.assertEqual(err.message_in("en"), "Daily quota of 100 emails reached.")
88
+ self.assertEqual(len(api.requests), 1)
89
+
90
+ def test_validation_field_messages(self):
91
+ api = FakeApi([(422, {"statusCode": 422, "name": "validation_error", "message": "Write a subject.",
92
+ "errors": {"subject": ["required"]}, "fieldMessagesTr": {"subject": "Bir konu yazın."}}, None)])
93
+ client = Mittena("k", base_url=api.base_url)
94
+ with self.assertRaises(MittenaError) as ctx:
95
+ client.templates.create({"name": "x"})
96
+ api.close()
97
+ self.assertEqual(ctx.exception.errors, {"subject": ["required"]})
98
+ self.assertEqual(ctx.exception.field_messages_tr["subject"], "Bir konu yazın.")
99
+
100
+ def test_list_query_and_cursor(self):
101
+ api = FakeApi([
102
+ (200, {"data": [{"id": "em_3"}, {"id": "em_2"}], "hasMore": True}, None),
103
+ (200, {"data": [{"id": "em_1"}], "hasMore": False}, None),
104
+ ])
105
+ client = Mittena("k", base_url=api.base_url)
106
+ ids = [e["id"] for e in client.emails.list_all(status="bounced", from_="a@acme.com", limit=2)]
107
+ api.close()
108
+ self.assertEqual(ids, ["em_3", "em_2", "em_1"])
109
+ self.assertEqual(api.requests[0]["path"], "/v1/emails?status=bounced&from=a%40acme.com&limit=2")
110
+ self.assertEqual(api.requests[1]["path"], "/v1/emails?status=bounced&from=a%40acme.com&limit=2&after=em_2")
111
+
112
+ def test_path_is_escaped(self):
113
+ api = FakeApi([(200, {}, None)])
114
+ Mittena("k", base_url=api.base_url).suppressions.remove("a+b@example.com")
115
+ api.close()
116
+ self.assertEqual(api.requests[0]["path"], "/v1/suppressions/a%2Bb%40example.com")
117
+
118
+ def test_missing_key(self):
119
+ import os
120
+ saved = os.environ.pop("MITTENA_API_KEY", None)
121
+ try:
122
+ with self.assertRaises(ValueError):
123
+ Mittena()
124
+ finally:
125
+ if saved:
126
+ os.environ["MITTENA_API_KEY"] = saved
127
+
128
+
129
+ class WebhookTests(unittest.TestCase):
130
+ def test_fixed_vector(self):
131
+ header = "t=1763460002,v1=b403bde9773ee1d4247198e8113a0bfa05a4ccc48cb749d67969bbb91ad17505"
132
+ self.assertEqual(Webhooks.sign("{}", "whsec_x", 1763460002), header)
133
+ self.assertEqual(Webhooks.verify("{}", header, "whsec_x", now=1763460002), {})
134
+
135
+ def test_rejects_tampering_and_old(self):
136
+ body = json.dumps({"type": "email.delivered", "data": {"emailId": "em_1"}})
137
+ header = Webhooks.sign(body, "whsec_t")
138
+ self.assertEqual(Webhooks.verify(body.encode(), header, "whsec_t")["data"]["emailId"], "em_1")
139
+ with self.assertRaises(WebhookVerificationError):
140
+ Webhooks.verify(body + " ", header, "whsec_t")
141
+ with self.assertRaises(WebhookVerificationError):
142
+ Webhooks.verify(body, header, "whsec_other")
143
+ with self.assertRaises(WebhookVerificationError):
144
+ Webhooks.verify(body, Webhooks.sign(body, "whsec_t", int(time.time()) - 600), "whsec_t")
145
+ with self.assertRaises(WebhookVerificationError):
146
+ Webhooks.verify(body, "garbage", "whsec_t")
147
+
148
+
149
+ if __name__ == "__main__":
150
+ unittest.main()