mailmolt 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.
- mailmolt-0.1.0/PKG-INFO +64 -0
- mailmolt-0.1.0/README.md +55 -0
- mailmolt-0.1.0/pyproject.toml +18 -0
- mailmolt-0.1.0/setup.cfg +4 -0
- mailmolt-0.1.0/src/mailmolt/__init__.py +354 -0
- mailmolt-0.1.0/src/mailmolt/cli.py +62 -0
- mailmolt-0.1.0/src/mailmolt.egg-info/PKG-INFO +64 -0
- mailmolt-0.1.0/src/mailmolt.egg-info/SOURCES.txt +9 -0
- mailmolt-0.1.0/src/mailmolt.egg-info/dependency_links.txt +1 -0
- mailmolt-0.1.0/src/mailmolt.egg-info/entry_points.txt +2 -0
- mailmolt-0.1.0/src/mailmolt.egg-info/top_level.txt +1 -0
mailmolt-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mailmolt
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for the MailMolt transactional email API: template sends, recipient lists, and HMAC-verified webhooks.
|
|
5
|
+
Author:
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# mailmolt
|
|
11
|
+
|
|
12
|
+
`mailmolt` is the Python SDK for the MailMolt transactional email API. It sends transactional email, manages templates and recipients, and verifies inbound webhook deliveries with HMAC-SHA256 signatures — the same surface as the official TypeScript SDK, so cross-stack teams share one mental model.
|
|
13
|
+
|
|
14
|
+
The client is sync-first with an async twin, returns typed responses, and exposes both a high-level `mail.send(...)` and a low-level per-resource API for templates, lists, and suppression entries.
|
|
15
|
+
|
|
16
|
+
## Features
|
|
17
|
+
|
|
18
|
+
- `mail.send(to, template, data)` — send a transactional message with a template + vars.
|
|
19
|
+
- Template and recipient-list management: `templates`, `lists`, `recipients`.
|
|
20
|
+
- HMAC-SHA256 webhook verification with constant-time compare.
|
|
21
|
+
- Sync (`MailMolt`) and async (`AsyncMailMolt`) clients on `httpx`.
|
|
22
|
+
- Per-message metadata, tags, and attachment helpers.
|
|
23
|
+
- Idempotency keys and retries for safe delivery under transient failures.
|
|
24
|
+
- Structured errors: `MailMoltError`, `RateLimitError`, `ValidationError`.
|
|
25
|
+
|
|
26
|
+
## Installation
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install mailmolt
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Quick start
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from mailmolt import MailMolt
|
|
36
|
+
|
|
37
|
+
mm = MailMolt(api_key="mm_live_...")
|
|
38
|
+
|
|
39
|
+
mm.mail.send(
|
|
40
|
+
to="ana@example.com",
|
|
41
|
+
template="welcome",
|
|
42
|
+
data={"first_name": "Ana", "verify_url": "https://app.example/verify/abc"},
|
|
43
|
+
)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from mailmolt import verify_webhook
|
|
48
|
+
|
|
49
|
+
event = verify_webhook(body=request.body, signature=request.headers["X-MailMolt-Signature"], secret="whsec_...")
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## API
|
|
53
|
+
|
|
54
|
+
- `MailMolt(api_key)` — sync client; `.mail`, `.templates`, `.lists`, `.recipients`, `.webhooks`.
|
|
55
|
+
- `mailmolt.verify_webhook(body, signature, secret)` — return the parsed event or raise.
|
|
56
|
+
- `mailmolt.errors.MailMoltError` — base error; subclasses for auth, rate limit, validation.
|
|
57
|
+
|
|
58
|
+
## Configuration
|
|
59
|
+
|
|
60
|
+
Set `MAILMOLT_API_KEY` for the client and `MAILMOLT_WEBHOOK_SECRET` for signature verification. Override the API host with `MAILMOLT_API_URL` for a regional endpoint.
|
|
61
|
+
|
|
62
|
+
## License
|
|
63
|
+
|
|
64
|
+
MIT
|
mailmolt-0.1.0/README.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# mailmolt
|
|
2
|
+
|
|
3
|
+
`mailmolt` is the Python SDK for the MailMolt transactional email API. It sends transactional email, manages templates and recipients, and verifies inbound webhook deliveries with HMAC-SHA256 signatures — the same surface as the official TypeScript SDK, so cross-stack teams share one mental model.
|
|
4
|
+
|
|
5
|
+
The client is sync-first with an async twin, returns typed responses, and exposes both a high-level `mail.send(...)` and a low-level per-resource API for templates, lists, and suppression entries.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- `mail.send(to, template, data)` — send a transactional message with a template + vars.
|
|
10
|
+
- Template and recipient-list management: `templates`, `lists`, `recipients`.
|
|
11
|
+
- HMAC-SHA256 webhook verification with constant-time compare.
|
|
12
|
+
- Sync (`MailMolt`) and async (`AsyncMailMolt`) clients on `httpx`.
|
|
13
|
+
- Per-message metadata, tags, and attachment helpers.
|
|
14
|
+
- Idempotency keys and retries for safe delivery under transient failures.
|
|
15
|
+
- Structured errors: `MailMoltError`, `RateLimitError`, `ValidationError`.
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install mailmolt
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from mailmolt import MailMolt
|
|
27
|
+
|
|
28
|
+
mm = MailMolt(api_key="mm_live_...")
|
|
29
|
+
|
|
30
|
+
mm.mail.send(
|
|
31
|
+
to="ana@example.com",
|
|
32
|
+
template="welcome",
|
|
33
|
+
data={"first_name": "Ana", "verify_url": "https://app.example/verify/abc"},
|
|
34
|
+
)
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from mailmolt import verify_webhook
|
|
39
|
+
|
|
40
|
+
event = verify_webhook(body=request.body, signature=request.headers["X-MailMolt-Signature"], secret="whsec_...")
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## API
|
|
44
|
+
|
|
45
|
+
- `MailMolt(api_key)` — sync client; `.mail`, `.templates`, `.lists`, `.recipients`, `.webhooks`.
|
|
46
|
+
- `mailmolt.verify_webhook(body, signature, secret)` — return the parsed event or raise.
|
|
47
|
+
- `mailmolt.errors.MailMoltError` — base error; subclasses for auth, rate limit, validation.
|
|
48
|
+
|
|
49
|
+
## Configuration
|
|
50
|
+
|
|
51
|
+
Set `MAILMOLT_API_KEY` for the client and `MAILMOLT_WEBHOOK_SECRET` for signature verification. Override the API host with `MAILMOLT_API_URL` for a regional endpoint.
|
|
52
|
+
|
|
53
|
+
## License
|
|
54
|
+
|
|
55
|
+
MIT
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "mailmolt"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python SDK for the MailMolt transactional email API: template sends, recipient lists, and HMAC-verified webhooks."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [{name = ""}]
|
|
13
|
+
|
|
14
|
+
[project.scripts]
|
|
15
|
+
mailmolt = "mailmolt.cli:main"
|
|
16
|
+
|
|
17
|
+
[tool.setuptools.packages.find]
|
|
18
|
+
where = ["src"]
|
mailmolt-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
"""mailmolt — Python SDK for the MailMolt transactional email API.
|
|
2
|
+
|
|
3
|
+
Send transactional email from templates, manage recipients and suppression
|
|
4
|
+
lists, and verify inbound webhook deliveries with HMAC-SHA256 signatures.
|
|
5
|
+
The HTTP layer is injectable (:class:`Transport`); the default uses stdlib
|
|
6
|
+
``urllib.request``. Sync (:class:`MailMolt`) and async (:class:`AsyncMailMolt`)
|
|
7
|
+
clients share one surface.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import base64
|
|
14
|
+
import hashlib
|
|
15
|
+
import hmac
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import Any, Dict, Iterable, List, Optional, Union
|
|
20
|
+
from urllib import error as urllib_error
|
|
21
|
+
from urllib import request as urllib_request
|
|
22
|
+
|
|
23
|
+
__version__ = "0.1.0"
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"MailMolt",
|
|
27
|
+
"AsyncMailMolt",
|
|
28
|
+
"Transport",
|
|
29
|
+
"UrllibTransport",
|
|
30
|
+
"Response",
|
|
31
|
+
"Message",
|
|
32
|
+
"Template",
|
|
33
|
+
"MailMoltError",
|
|
34
|
+
"AuthenticationError",
|
|
35
|
+
"RateLimitError",
|
|
36
|
+
"ValidationError",
|
|
37
|
+
"WebhookVerificationError",
|
|
38
|
+
"verify_webhook",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
DEFAULT_BASE_URL = "https://api.mailmolt.com"
|
|
42
|
+
SIGNATURE_TOLERANCE_SECONDS = 300
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class MailMoltError(Exception):
|
|
46
|
+
"""Base error for all MailMolt API failures."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class AuthenticationError(MailMoltError):
|
|
50
|
+
"""Invalid or missing API key."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class RateLimitError(MailMoltError):
|
|
54
|
+
"""HTTP 429 from the MailMolt API."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ValidationError(MailMoltError):
|
|
58
|
+
"""Bad request parameters (missing recipient, malformed template, ...)."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class WebhookVerificationError(MailMoltError):
|
|
62
|
+
"""Webhook signature failed HMAC verification."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass
|
|
66
|
+
class Response:
|
|
67
|
+
status: int
|
|
68
|
+
data: Any
|
|
69
|
+
headers: Dict[str, str] = field(default_factory=dict)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Transport:
|
|
73
|
+
"""Pluggable HTTP transport for the MailMolt API."""
|
|
74
|
+
|
|
75
|
+
def request(
|
|
76
|
+
self,
|
|
77
|
+
method: str,
|
|
78
|
+
url: str,
|
|
79
|
+
*,
|
|
80
|
+
headers: Optional[Dict[str, str]] = None,
|
|
81
|
+
json_body: Any = None,
|
|
82
|
+
timeout: float = 30.0,
|
|
83
|
+
) -> Response:
|
|
84
|
+
raise NotImplementedError
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class UrllibTransport(Transport):
|
|
88
|
+
"""Default stdlib transport."""
|
|
89
|
+
|
|
90
|
+
def request(
|
|
91
|
+
self,
|
|
92
|
+
method: str,
|
|
93
|
+
url: str,
|
|
94
|
+
*,
|
|
95
|
+
headers: Optional[Dict[str, str]] = None,
|
|
96
|
+
json_body: Any = None,
|
|
97
|
+
timeout: float = 30.0,
|
|
98
|
+
) -> Response:
|
|
99
|
+
body = None
|
|
100
|
+
hdrs = dict(headers or {})
|
|
101
|
+
if json_body is not None:
|
|
102
|
+
body = json.dumps(json_body).encode("utf-8")
|
|
103
|
+
hdrs.setdefault("Content-Type", "application/json")
|
|
104
|
+
req = urllib_request.Request(url, data=body, headers=hdrs, method=method)
|
|
105
|
+
try:
|
|
106
|
+
with urllib_request.urlopen(req, timeout=timeout) as resp:
|
|
107
|
+
raw = resp.read()
|
|
108
|
+
return Response(resp.status, json.loads(raw) if raw else None, dict(resp.headers))
|
|
109
|
+
except urllib_error.HTTPError as exc:
|
|
110
|
+
raw = exc.read()
|
|
111
|
+
try:
|
|
112
|
+
data = json.loads(raw) if raw else None
|
|
113
|
+
except ValueError:
|
|
114
|
+
data = {"message": raw.decode("utf-8", "replace")}
|
|
115
|
+
return Response(exc.code, data, dict(exc.headers))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass
|
|
119
|
+
class Message:
|
|
120
|
+
id: str
|
|
121
|
+
to: str
|
|
122
|
+
template: str
|
|
123
|
+
status: str = "queued"
|
|
124
|
+
message_id: str = ""
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@dataclass
|
|
128
|
+
class Template:
|
|
129
|
+
id: str
|
|
130
|
+
name: str
|
|
131
|
+
subject: str = ""
|
|
132
|
+
locale: str = "en"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _require_email(to: str) -> None:
|
|
136
|
+
if not to or "@" not in to:
|
|
137
|
+
raise ValidationError(f"invalid recipient address: {to!r}")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class _MailAPI:
|
|
141
|
+
"""High-level ``mail.send(...)`` plus batch sending."""
|
|
142
|
+
|
|
143
|
+
def __init__(self, client: "MailMolt") -> None:
|
|
144
|
+
self._client = client
|
|
145
|
+
|
|
146
|
+
def send(
|
|
147
|
+
self,
|
|
148
|
+
to: str,
|
|
149
|
+
template: str,
|
|
150
|
+
data: Optional[Dict[str, Any]] = None,
|
|
151
|
+
*,
|
|
152
|
+
tags: Optional[List[str]] = None,
|
|
153
|
+
metadata: Optional[Dict[str, Any]] = None,
|
|
154
|
+
attachments: Optional[List[Dict[str, str]]] = None,
|
|
155
|
+
idempotency_key: Optional[str] = None,
|
|
156
|
+
) -> Message:
|
|
157
|
+
"""Send one transactional message using a template + variables."""
|
|
158
|
+
_require_email(to)
|
|
159
|
+
headers = {"Idempotency-Key": idempotency_key} if idempotency_key else None
|
|
160
|
+
payload = {
|
|
161
|
+
"to": to,
|
|
162
|
+
"template": template,
|
|
163
|
+
"data": data or {},
|
|
164
|
+
"tags": tags or [],
|
|
165
|
+
"metadata": metadata or {},
|
|
166
|
+
"attachments": attachments or [],
|
|
167
|
+
}
|
|
168
|
+
resp_data = self._client._request("POST", "/v1/mail/send", payload, headers=headers)
|
|
169
|
+
return Message(
|
|
170
|
+
id=resp_data.get("id", ""),
|
|
171
|
+
to=to,
|
|
172
|
+
template=template,
|
|
173
|
+
status=resp_data.get("status", "queued"),
|
|
174
|
+
message_id=resp_data.get("message_id", ""),
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
def send_batch(self, messages: Iterable[Dict[str, Any]]) -> List[Message]:
|
|
178
|
+
"""Send several messages at once; each dict mirrors ``send`` kwargs."""
|
|
179
|
+
out: List[Message] = []
|
|
180
|
+
for spec in messages:
|
|
181
|
+
out.append(self.send(**spec))
|
|
182
|
+
return out
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class _TemplatesAPI:
|
|
186
|
+
def __init__(self, client: "MailMolt") -> None:
|
|
187
|
+
self._client = client
|
|
188
|
+
|
|
189
|
+
def create(self, name: str, *, subject: str, html: str, locale: str = "en") -> Template:
|
|
190
|
+
data = self._client._request(
|
|
191
|
+
"POST", "/v1/templates",
|
|
192
|
+
{"name": name, "subject": subject, "html": html, "locale": locale},
|
|
193
|
+
)
|
|
194
|
+
return Template(id=data.get("id", ""), name=name, subject=subject, locale=locale)
|
|
195
|
+
|
|
196
|
+
def list(self) -> List[Template]:
|
|
197
|
+
data = self._client._request("GET", "/v1/templates")
|
|
198
|
+
return [
|
|
199
|
+
Template(id=t.get("id", ""), name=t.get("name", ""), subject=t.get("subject", ""), locale=t.get("locale", "en"))
|
|
200
|
+
for t in data.get("templates", [])
|
|
201
|
+
]
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class _ListsAPI:
|
|
205
|
+
def __init__(self, client: "MailMolt") -> None:
|
|
206
|
+
self._client = client
|
|
207
|
+
|
|
208
|
+
def create(self, name: str) -> Dict[str, Any]:
|
|
209
|
+
return dict(self._client._request("POST", "/v1/lists", {"name": name}))
|
|
210
|
+
|
|
211
|
+
def add(self, list_id: str, email: str) -> Dict[str, Any]:
|
|
212
|
+
_require_email(email)
|
|
213
|
+
return dict(self._client._request("POST", f"/v1/lists/{list_id}/recipients", {"email": email}))
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class _RecipientsAPI:
|
|
217
|
+
def __init__(self, client: "MailMolt") -> None:
|
|
218
|
+
self._client = client
|
|
219
|
+
|
|
220
|
+
def suppress(self, email: str, *, reason: str = "manual") -> Dict[str, Any]:
|
|
221
|
+
return dict(self._client._request("POST", "/v1/recipients/suppress", {"email": email, "reason": reason}))
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class _WebhooksAPI:
|
|
225
|
+
def __init__(self, client: "MailMolt") -> None:
|
|
226
|
+
self._client = client
|
|
227
|
+
|
|
228
|
+
def create(self, url: str, *, events: Optional[List[str]] = None) -> Dict[str, Any]:
|
|
229
|
+
return dict(self._client._request("POST", "/v1/webhooks", {"url": url, "events": events or ["delivered", "bounced"]}))
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class MailMolt:
|
|
233
|
+
"""Sync client for the MailMolt transactional email API."""
|
|
234
|
+
|
|
235
|
+
def __init__(
|
|
236
|
+
self,
|
|
237
|
+
api_key: Optional[str] = None,
|
|
238
|
+
*,
|
|
239
|
+
base_url: Optional[str] = None,
|
|
240
|
+
transport: Optional[Transport] = None,
|
|
241
|
+
timeout: float = 30.0,
|
|
242
|
+
) -> None:
|
|
243
|
+
self.api_key = api_key or os.environ.get("MAILMOLT_API_KEY", "")
|
|
244
|
+
if not self.api_key:
|
|
245
|
+
raise AuthenticationError("no API key: pass api_key= or set MAILMOLT_API_KEY")
|
|
246
|
+
self.base_url = (base_url or os.environ.get("MAILMOLT_API_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
247
|
+
self.transport = transport or UrllibTransport()
|
|
248
|
+
self.timeout = timeout
|
|
249
|
+
self.mail = _MailAPI(self)
|
|
250
|
+
self.templates = _TemplatesAPI(self)
|
|
251
|
+
self.lists = _ListsAPI(self)
|
|
252
|
+
self.recipients = _RecipientsAPI(self)
|
|
253
|
+
self.webhooks = _WebhooksAPI(self)
|
|
254
|
+
|
|
255
|
+
def _request(
|
|
256
|
+
self,
|
|
257
|
+
method: str,
|
|
258
|
+
path: str,
|
|
259
|
+
json_body: Any = None,
|
|
260
|
+
headers: Optional[Dict[str, str]] = None,
|
|
261
|
+
) -> Any:
|
|
262
|
+
url = f"{self.base_url}{path}"
|
|
263
|
+
hdrs = {"Authorization": f"Bearer {self.api_key}"}
|
|
264
|
+
if headers:
|
|
265
|
+
hdrs.update(headers)
|
|
266
|
+
resp = self.transport.request(method, url, headers=hdrs, json_body=json_body, timeout=self.timeout)
|
|
267
|
+
if resp.status in (401, 403):
|
|
268
|
+
raise AuthenticationError(f"authentication failed: HTTP {resp.status}")
|
|
269
|
+
if resp.status == 429:
|
|
270
|
+
raise RateLimitError("rate limited by MailMolt")
|
|
271
|
+
if resp.status >= 400:
|
|
272
|
+
message = resp.data.get("message", "") if isinstance(resp.data, dict) else ""
|
|
273
|
+
raise ValidationError(f"HTTP {resp.status}: {message}")
|
|
274
|
+
return resp.data
|
|
275
|
+
|
|
276
|
+
def as_async(self) -> "AsyncMailMolt":
|
|
277
|
+
"""Return an async twin sharing this client's configuration."""
|
|
278
|
+
return AsyncMailMolt(
|
|
279
|
+
self.api_key,
|
|
280
|
+
base_url=self.base_url,
|
|
281
|
+
transport=self.transport,
|
|
282
|
+
timeout=self.timeout,
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class AsyncMailMolt(MailMolt):
|
|
287
|
+
"""Async twin of :class:`MailMolt` — same surface, coroutine methods."""
|
|
288
|
+
|
|
289
|
+
async def _request_async(self, method: str, path: str, json_body: Any = None, headers: Optional[Dict[str, str]] = None) -> Any:
|
|
290
|
+
return await asyncio.to_thread(self._request, method, path, json_body, headers)
|
|
291
|
+
|
|
292
|
+
async def send(
|
|
293
|
+
self,
|
|
294
|
+
to: str,
|
|
295
|
+
template: str,
|
|
296
|
+
data: Optional[Dict[str, Any]] = None,
|
|
297
|
+
**kwargs: Any,
|
|
298
|
+
) -> Message:
|
|
299
|
+
return await asyncio.to_thread(self.mail.send, to, template, data, **kwargs)
|
|
300
|
+
|
|
301
|
+
async def templates_list(self) -> List[Template]:
|
|
302
|
+
return await asyncio.to_thread(self.templates.list)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def verify_webhook(
|
|
306
|
+
body: Union[str, bytes],
|
|
307
|
+
signature: str,
|
|
308
|
+
secret: str,
|
|
309
|
+
*,
|
|
310
|
+
tolerance_seconds: int = SIGNATURE_TOLERANCE_SECONDS,
|
|
311
|
+
now: Optional[float] = None,
|
|
312
|
+
) -> Dict[str, Any]:
|
|
313
|
+
"""Verify an inbound webhook's ``X-MailMolt-Signature`` header.
|
|
314
|
+
|
|
315
|
+
The signature may be a bare hex digest or a ``t=<ts>,v1=<hex>`` pair.
|
|
316
|
+
Returns the parsed JSON event; raises :class:`WebhookVerificationError`
|
|
317
|
+
on a bad signature, stale timestamp, or unparsable body.
|
|
318
|
+
"""
|
|
319
|
+
if isinstance(body, str):
|
|
320
|
+
body = body.encode("utf-8")
|
|
321
|
+
|
|
322
|
+
timestamp: Optional[str] = None
|
|
323
|
+
provided = ""
|
|
324
|
+
for part in signature.split(","):
|
|
325
|
+
part = part.strip()
|
|
326
|
+
if part.startswith("t="):
|
|
327
|
+
timestamp = part[2:]
|
|
328
|
+
elif part.startswith("v1="):
|
|
329
|
+
provided = part[3:]
|
|
330
|
+
if not provided:
|
|
331
|
+
provided = signature.strip()
|
|
332
|
+
|
|
333
|
+
if timestamp is not None:
|
|
334
|
+
import time as _time
|
|
335
|
+
|
|
336
|
+
current = now if now is not None else _time.time()
|
|
337
|
+
try:
|
|
338
|
+
age = abs(current - float(timestamp))
|
|
339
|
+
except ValueError:
|
|
340
|
+
raise WebhookVerificationError("malformed signature timestamp")
|
|
341
|
+
if age > tolerance_seconds:
|
|
342
|
+
raise WebhookVerificationError("signature timestamp outside tolerance")
|
|
343
|
+
|
|
344
|
+
expected = hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
|
|
345
|
+
if not hmac.compare_digest(expected, provided):
|
|
346
|
+
raise WebhookVerificationError("signature mismatch")
|
|
347
|
+
|
|
348
|
+
try:
|
|
349
|
+
event = json.loads(body.decode("utf-8"))
|
|
350
|
+
except (ValueError, UnicodeDecodeError):
|
|
351
|
+
raise WebhookVerificationError("signed body is not valid JSON")
|
|
352
|
+
if not isinstance(event, dict):
|
|
353
|
+
raise WebhookVerificationError("signed body is not a JSON object")
|
|
354
|
+
return event
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""CLI for the MailMolt SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from typing import List, Optional
|
|
9
|
+
|
|
10
|
+
from . import (
|
|
11
|
+
AuthenticationError,
|
|
12
|
+
MailMolt,
|
|
13
|
+
MailMoltError,
|
|
14
|
+
verify_webhook,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
19
|
+
parser = argparse.ArgumentParser(prog="mailmolt", description="MailMolt transactional email CLI")
|
|
20
|
+
parser.add_argument("--base-url", default=None, help="override the API host")
|
|
21
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
22
|
+
|
|
23
|
+
send = sub.add_parser("send", help="send a transactional message")
|
|
24
|
+
send.add_argument("--to", required=True)
|
|
25
|
+
send.add_argument("--template", required=True)
|
|
26
|
+
send.add_argument("--data", default="{}", help="template variables as JSON")
|
|
27
|
+
send.add_argument("--idempotency-key", default=None)
|
|
28
|
+
|
|
29
|
+
tpl = sub.add_parser("templates", help="list templates")
|
|
30
|
+
|
|
31
|
+
verify = sub.add_parser("verify", help="verify a webhook delivery")
|
|
32
|
+
verify.add_argument("--body", required=True, help="raw signed body (JSON)")
|
|
33
|
+
verify.add_argument("--signature", required=True, help="X-MailMolt-Signature header")
|
|
34
|
+
verify.add_argument("--secret", required=True, help="whsec_... signing secret")
|
|
35
|
+
return parser
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
39
|
+
parser = _build_parser()
|
|
40
|
+
args = parser.parse_args(argv)
|
|
41
|
+
try:
|
|
42
|
+
if args.command == "verify":
|
|
43
|
+
event = verify_webhook(args.body, args.signature, args.secret)
|
|
44
|
+
print(json.dumps(event, indent=2, sort_keys=True))
|
|
45
|
+
return 0
|
|
46
|
+
client = MailMolt(base_url=args.base_url)
|
|
47
|
+
if args.command == "send":
|
|
48
|
+
msg = client.mail.send(
|
|
49
|
+
args.to, args.template, json.loads(args.data), idempotency_key=args.idempotency_key
|
|
50
|
+
)
|
|
51
|
+
print(json.dumps({"id": msg.id, "status": msg.status, "to": msg.to}))
|
|
52
|
+
elif args.command == "templates":
|
|
53
|
+
for t in client.templates.list():
|
|
54
|
+
print(json.dumps({"id": t.id, "name": t.name, "subject": t.subject}))
|
|
55
|
+
except (MailMoltError, ValueError) as exc:
|
|
56
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
57
|
+
return 1
|
|
58
|
+
return 0
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
if __name__ == "__main__": # pragma: no cover
|
|
62
|
+
sys.exit(main())
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mailmolt
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for the MailMolt transactional email API: template sends, recipient lists, and HMAC-verified webhooks.
|
|
5
|
+
Author:
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# mailmolt
|
|
11
|
+
|
|
12
|
+
`mailmolt` is the Python SDK for the MailMolt transactional email API. It sends transactional email, manages templates and recipients, and verifies inbound webhook deliveries with HMAC-SHA256 signatures — the same surface as the official TypeScript SDK, so cross-stack teams share one mental model.
|
|
13
|
+
|
|
14
|
+
The client is sync-first with an async twin, returns typed responses, and exposes both a high-level `mail.send(...)` and a low-level per-resource API for templates, lists, and suppression entries.
|
|
15
|
+
|
|
16
|
+
## Features
|
|
17
|
+
|
|
18
|
+
- `mail.send(to, template, data)` — send a transactional message with a template + vars.
|
|
19
|
+
- Template and recipient-list management: `templates`, `lists`, `recipients`.
|
|
20
|
+
- HMAC-SHA256 webhook verification with constant-time compare.
|
|
21
|
+
- Sync (`MailMolt`) and async (`AsyncMailMolt`) clients on `httpx`.
|
|
22
|
+
- Per-message metadata, tags, and attachment helpers.
|
|
23
|
+
- Idempotency keys and retries for safe delivery under transient failures.
|
|
24
|
+
- Structured errors: `MailMoltError`, `RateLimitError`, `ValidationError`.
|
|
25
|
+
|
|
26
|
+
## Installation
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install mailmolt
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Quick start
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from mailmolt import MailMolt
|
|
36
|
+
|
|
37
|
+
mm = MailMolt(api_key="mm_live_...")
|
|
38
|
+
|
|
39
|
+
mm.mail.send(
|
|
40
|
+
to="ana@example.com",
|
|
41
|
+
template="welcome",
|
|
42
|
+
data={"first_name": "Ana", "verify_url": "https://app.example/verify/abc"},
|
|
43
|
+
)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from mailmolt import verify_webhook
|
|
48
|
+
|
|
49
|
+
event = verify_webhook(body=request.body, signature=request.headers["X-MailMolt-Signature"], secret="whsec_...")
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## API
|
|
53
|
+
|
|
54
|
+
- `MailMolt(api_key)` — sync client; `.mail`, `.templates`, `.lists`, `.recipients`, `.webhooks`.
|
|
55
|
+
- `mailmolt.verify_webhook(body, signature, secret)` — return the parsed event or raise.
|
|
56
|
+
- `mailmolt.errors.MailMoltError` — base error; subclasses for auth, rate limit, validation.
|
|
57
|
+
|
|
58
|
+
## Configuration
|
|
59
|
+
|
|
60
|
+
Set `MAILMOLT_API_KEY` for the client and `MAILMOLT_WEBHOOK_SECRET` for signature verification. Override the API host with `MAILMOLT_API_URL` for a regional endpoint.
|
|
61
|
+
|
|
62
|
+
## License
|
|
63
|
+
|
|
64
|
+
MIT
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/mailmolt/__init__.py
|
|
4
|
+
src/mailmolt/cli.py
|
|
5
|
+
src/mailmolt.egg-info/PKG-INFO
|
|
6
|
+
src/mailmolt.egg-info/SOURCES.txt
|
|
7
|
+
src/mailmolt.egg-info/dependency_links.txt
|
|
8
|
+
src/mailmolt.egg-info/entry_points.txt
|
|
9
|
+
src/mailmolt.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mailmolt
|