receive-pk 1.0.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.
- receive_pk-1.0.0/PKG-INFO +30 -0
- receive_pk-1.0.0/README.md +20 -0
- receive_pk-1.0.0/pyproject.toml +18 -0
- receive_pk-1.0.0/receive_pk/__init__.py +359 -0
- receive_pk-1.0.0/receive_pk.egg-info/PKG-INFO +30 -0
- receive_pk-1.0.0/receive_pk.egg-info/SOURCES.txt +7 -0
- receive_pk-1.0.0/receive_pk.egg-info/dependency_links.txt +1 -0
- receive_pk-1.0.0/receive_pk.egg-info/top_level.txt +1 -0
- receive_pk-1.0.0/setup.cfg +4 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: receive-pk
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: The official Receive SDK: send email, track who read it, verify webhooks. No dependencies.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://receive.pk/docs/sdks/python
|
|
7
|
+
Keywords: email,transactional email,otp,receive,webhooks
|
|
8
|
+
Requires-Python: >=3.8
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# receive_pk
|
|
12
|
+
|
|
13
|
+
The official [Receive](https://receive.pk) SDK for Python.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { Receive } from "receive_pk";
|
|
17
|
+
|
|
18
|
+
const receive = new Receive(process.env.RECEIVE_API_KEY);
|
|
19
|
+
const { data, error } = await receive.emails.send({
|
|
20
|
+
from: "Acme <hello@mail.acme.com>",
|
|
21
|
+
to: "ava@example.com",
|
|
22
|
+
subject: "Welcome",
|
|
23
|
+
html: "<p>Thanks for joining.</p>",
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Zero dependencies. Safe retries, automatic pacing, any-size batches, request-aware `requestedFrom`, and one-line webhook checks.
|
|
28
|
+
|
|
29
|
+
Full guide: https://receive.pk/docs/sdks/python
|
|
30
|
+
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# receive_pk
|
|
2
|
+
|
|
3
|
+
The official [Receive](https://receive.pk) SDK for Python.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { Receive } from "receive_pk";
|
|
7
|
+
|
|
8
|
+
const receive = new Receive(process.env.RECEIVE_API_KEY);
|
|
9
|
+
const { data, error } = await receive.emails.send({
|
|
10
|
+
from: "Acme <hello@mail.acme.com>",
|
|
11
|
+
to: "ava@example.com",
|
|
12
|
+
subject: "Welcome",
|
|
13
|
+
html: "<p>Thanks for joining.</p>",
|
|
14
|
+
});
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Zero dependencies. Safe retries, automatic pacing, any-size batches, request-aware `requestedFrom`, and one-line webhook checks.
|
|
18
|
+
|
|
19
|
+
Full guide: https://receive.pk/docs/sdks/python
|
|
20
|
+
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "receive-pk"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "The official Receive SDK: send email, track who read it, verify webhooks. No dependencies."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
keywords = ["email", "transactional email", "otp", "receive", "webhooks"]
|
|
13
|
+
|
|
14
|
+
[project.urls]
|
|
15
|
+
Homepage = "https://receive.pk/docs/sdks/python"
|
|
16
|
+
|
|
17
|
+
[tool.setuptools]
|
|
18
|
+
packages = ["receive_pk"]
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The official Receive SDK for Python.
|
|
3
|
+
|
|
4
|
+
from receive_pk import Receive
|
|
5
|
+
receive = Receive("rcv_...")
|
|
6
|
+
email = receive.emails.send({"from": "...", "to": "...", "subject": "...", "html": "..."})
|
|
7
|
+
|
|
8
|
+
No dependencies: only the standard library. Python 3.8+.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import base64
|
|
13
|
+
import hashlib
|
|
14
|
+
import hmac
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import random
|
|
18
|
+
import re
|
|
19
|
+
import threading
|
|
20
|
+
import time
|
|
21
|
+
import urllib.error
|
|
22
|
+
import urllib.parse
|
|
23
|
+
import urllib.request
|
|
24
|
+
import uuid
|
|
25
|
+
from datetime import datetime, timedelta, timezone
|
|
26
|
+
from typing import Any, Dict, Iterator, List, Optional, Union
|
|
27
|
+
|
|
28
|
+
__version__ = "1.0.0"
|
|
29
|
+
__all__ = ["Receive", "ReceiveError", "requested_from", "to_iso"]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ReceiveError(Exception):
|
|
33
|
+
"""Every failure. `code` is machine-readable ("invalid_api_key", "rate_limited", ...)."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, message: str, code: str, status_code: int):
|
|
36
|
+
super().__init__(message)
|
|
37
|
+
self.message = message
|
|
38
|
+
self.code = code
|
|
39
|
+
self.status_code = status_code
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def retryable(self) -> bool:
|
|
43
|
+
return self.status_code == 0 or self.status_code == 429 or self.status_code >= 500
|
|
44
|
+
|
|
45
|
+
def __repr__(self) -> str:
|
|
46
|
+
return f"ReceiveError(code={self.code!r}, status_code={self.status_code}, message={self.message!r})"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# ─────────────────────────── helpers ───────────────────────────
|
|
50
|
+
|
|
51
|
+
_IP = re.compile(r"^[0-9a-fA-F.:]{3,45}$")
|
|
52
|
+
_IN = re.compile(r"^in\s+(\d+(?:\.\d+)?)\s*(second|minute|hour|day|week)s?$", re.I)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _header(req: Any, name: str) -> Optional[str]:
|
|
56
|
+
headers = getattr(req, "headers", None)
|
|
57
|
+
if headers is not None:
|
|
58
|
+
v = headers.get(name) if hasattr(headers, "get") else None
|
|
59
|
+
if v:
|
|
60
|
+
return v
|
|
61
|
+
meta = getattr(req, "META", None) # Django
|
|
62
|
+
if meta:
|
|
63
|
+
return meta.get("HTTP_" + name.upper().replace("-", "_"))
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def requested_from(req: Any, **extra: Any) -> Dict[str, Any]:
|
|
68
|
+
"""The person's IP address and browser, read from the incoming request.
|
|
69
|
+
Works with Flask, Django, FastAPI/Starlette, and behind Cloudflare and most proxies."""
|
|
70
|
+
ip = _header(req, "CF-Connecting-IP") or _header(req, "X-Real-IP") or (_header(req, "X-Forwarded-For") or "").split(",")[0]
|
|
71
|
+
if not ip:
|
|
72
|
+
ip = getattr(req, "remote_addr", None) or (getattr(req, "META", {}) or {}).get("REMOTE_ADDR") or getattr(getattr(req, "client", None), "host", None) or ""
|
|
73
|
+
ip = ip.strip().replace("::ffff:", "")
|
|
74
|
+
ua = _header(req, "User-Agent") or ""
|
|
75
|
+
out: Dict[str, Any] = {}
|
|
76
|
+
if _IP.match(ip):
|
|
77
|
+
out["ip"] = ip
|
|
78
|
+
if ua:
|
|
79
|
+
out["user_agent"] = ua[:300]
|
|
80
|
+
out.update(extra)
|
|
81
|
+
return out
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def to_iso(when: Union[datetime, int, float, str]) -> str:
|
|
85
|
+
"""datetime, a unix time, an ISO text, or plain words like "in 10 minutes"."""
|
|
86
|
+
if isinstance(when, datetime):
|
|
87
|
+
return (when if when.tzinfo else when.replace(tzinfo=timezone.utc)).isoformat()
|
|
88
|
+
if isinstance(when, (int, float)):
|
|
89
|
+
return datetime.fromtimestamp(when, timezone.utc).isoformat()
|
|
90
|
+
m = _IN.match(when.strip())
|
|
91
|
+
if m:
|
|
92
|
+
unit = {"second": "seconds", "minute": "minutes", "hour": "hours", "day": "days", "week": "weeks"}[m.group(2).lower()]
|
|
93
|
+
return (datetime.now(timezone.utc) + timedelta(**{unit: float(m.group(1))})).isoformat()
|
|
94
|
+
return when
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _looks_like_request(v: Any) -> bool:
|
|
98
|
+
return not isinstance(v, dict) and (hasattr(v, "headers") or hasattr(v, "META"))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _attachment(a: Dict[str, Any]) -> Dict[str, Any]:
|
|
102
|
+
if a.get("path"):
|
|
103
|
+
with open(a["path"], "rb") as f:
|
|
104
|
+
content = base64.b64encode(f.read()).decode()
|
|
105
|
+
elif isinstance(a.get("content"), (bytes, bytearray)):
|
|
106
|
+
content = base64.b64encode(a["content"]).decode()
|
|
107
|
+
elif isinstance(a.get("content"), str):
|
|
108
|
+
content = a["content"] # already base64
|
|
109
|
+
else:
|
|
110
|
+
raise ReceiveError(f'Attachment "{a.get("filename")}" needs content or path.', "invalid_attachments", 422)
|
|
111
|
+
out = {"filename": a["filename"], "content": content}
|
|
112
|
+
if a.get("content_type"):
|
|
113
|
+
out["content_type"] = a["content_type"]
|
|
114
|
+
return out
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _normalize(e: Dict[str, Any]) -> Dict[str, Any]:
|
|
118
|
+
out = {k: v for k, v in e.items() if v is not None}
|
|
119
|
+
if "from_" in out:
|
|
120
|
+
out["from"] = out.pop("from_")
|
|
121
|
+
if out.get("scheduled_at") is not None:
|
|
122
|
+
out["scheduled_at"] = to_iso(out["scheduled_at"])
|
|
123
|
+
rf = out.get("requested_from")
|
|
124
|
+
if rf is not None and _looks_like_request(rf):
|
|
125
|
+
out["requested_from"] = requested_from(rf)
|
|
126
|
+
if isinstance(out.get("tags"), dict):
|
|
127
|
+
out["tags"] = [{"name": k, "value": str(v)} for k, v in out["tags"].items()]
|
|
128
|
+
if out.get("attachments"):
|
|
129
|
+
out["attachments"] = [_attachment(a) for a in out["attachments"]]
|
|
130
|
+
return out
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
# ─────────────────────────── the client ───────────────────────────
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class Receive:
|
|
137
|
+
def __init__(self, api_key: Optional[str] = None, *, base_url: Optional[str] = None, max_retries: int = 3, timeout: float = 30.0, debug: bool = False):
|
|
138
|
+
self.api_key = api_key or os.environ.get("RECEIVE_API_KEY", "")
|
|
139
|
+
self.base_url = (base_url or os.environ.get("RECEIVE_BASE_URL") or "https://receive.pk").rstrip("/")
|
|
140
|
+
self.max_retries = max_retries
|
|
141
|
+
self.timeout = timeout
|
|
142
|
+
self.debug = debug
|
|
143
|
+
self._window: List[float] = []
|
|
144
|
+
self._lock = threading.Lock()
|
|
145
|
+
self.emails = _Emails(self)
|
|
146
|
+
self.domains = _Domains(self)
|
|
147
|
+
self.audiences = _Audiences(self)
|
|
148
|
+
self.contacts = _Contacts(self)
|
|
149
|
+
self.suppressions = _Suppressions(self)
|
|
150
|
+
self.webhooks = _Webhooks()
|
|
151
|
+
|
|
152
|
+
def _pace(self) -> None:
|
|
153
|
+
"""Stays under the API's 10 requests a second, also across threads."""
|
|
154
|
+
while True:
|
|
155
|
+
with self._lock:
|
|
156
|
+
now = time.monotonic()
|
|
157
|
+
self._window = [t for t in self._window if now - t < 1]
|
|
158
|
+
if len(self._window) < 10:
|
|
159
|
+
self._window.append(now)
|
|
160
|
+
return
|
|
161
|
+
wait = 1 - (now - self._window[0]) + 0.005
|
|
162
|
+
time.sleep(wait)
|
|
163
|
+
|
|
164
|
+
def request(self, method: str, path: str, body: Any = None, headers: Optional[Dict[str, str]] = None) -> Any:
|
|
165
|
+
if not self.api_key:
|
|
166
|
+
raise ReceiveError('No API key. Pass it to Receive("rcv_...") or set RECEIVE_API_KEY.', "missing_api_key", 401)
|
|
167
|
+
data = None if body is None else json.dumps(body).encode()
|
|
168
|
+
h = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json", "User-Agent": f"receive-python/{__version__}", **(headers or {})}
|
|
169
|
+
last: Optional[ReceiveError] = None
|
|
170
|
+
for attempt in range(self.max_retries + 1):
|
|
171
|
+
if attempt:
|
|
172
|
+
time.sleep(min(8.0, 0.4 * 2 ** (attempt - 1)) + random.random() * 0.25)
|
|
173
|
+
self._pace()
|
|
174
|
+
started = time.monotonic()
|
|
175
|
+
try:
|
|
176
|
+
req = urllib.request.Request(self.base_url + "/api/v1" + path, data=data, method=method, headers=h)
|
|
177
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as res:
|
|
178
|
+
text = res.read().decode()
|
|
179
|
+
if self.debug:
|
|
180
|
+
print(f"[receive] {method} {path} -> {res.status} in {int((time.monotonic() - started) * 1000)} ms")
|
|
181
|
+
return json.loads(text) if text else None
|
|
182
|
+
except urllib.error.HTTPError as e:
|
|
183
|
+
text = e.read().decode(errors="replace")
|
|
184
|
+
try:
|
|
185
|
+
err = json.loads(text).get("error", {})
|
|
186
|
+
except ValueError:
|
|
187
|
+
err = {}
|
|
188
|
+
last = ReceiveError(err.get("message") or f"Request failed with status {e.code}.", err.get("code") or "http_error", e.code)
|
|
189
|
+
if self.debug:
|
|
190
|
+
print(f"[receive] {method} {path} -> {e.code} {last.code}")
|
|
191
|
+
if not last.retryable:
|
|
192
|
+
break
|
|
193
|
+
ra = e.headers.get("Retry-After") if e.headers else None
|
|
194
|
+
if ra and ra.isdigit():
|
|
195
|
+
time.sleep(min(int(ra), 30))
|
|
196
|
+
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
197
|
+
last = ReceiveError(f"Could not reach Receive: {e}", "network_error", 0)
|
|
198
|
+
assert last is not None
|
|
199
|
+
raise last
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _q(**p: Any) -> str:
|
|
203
|
+
p = {k: v for k, v in p.items() if v is not None}
|
|
204
|
+
return ("?" + urllib.parse.urlencode(p)) if p else ""
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _q_id(v: str) -> str:
|
|
208
|
+
return urllib.parse.quote(v, safe="")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _everything(load) -> Iterator[Dict[str, Any]]:
|
|
212
|
+
offset = 0
|
|
213
|
+
while True:
|
|
214
|
+
page = load(offset)
|
|
215
|
+
yield from page["data"]
|
|
216
|
+
if len(page["data"]) < page["limit"]:
|
|
217
|
+
return
|
|
218
|
+
offset += len(page["data"])
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class _Emails:
|
|
222
|
+
def __init__(self, c: Receive):
|
|
223
|
+
self._c = c
|
|
224
|
+
|
|
225
|
+
def send(self, email: Dict[str, Any], idempotency_key: Optional[str] = None) -> Dict[str, Any]:
|
|
226
|
+
"""Sends one email. Safe to retry: the same call never sends twice. Use "from" or from_."""
|
|
227
|
+
return self._c.request("POST", "/emails", _normalize(email), {"Idempotency-Key": idempotency_key or str(uuid.uuid4())})
|
|
228
|
+
|
|
229
|
+
create = send
|
|
230
|
+
|
|
231
|
+
def batch(self, emails: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
232
|
+
"""Any number of emails, sent in groups of 100. Results come back in the same order."""
|
|
233
|
+
out: List[Dict[str, Any]] = []
|
|
234
|
+
for i in range(0, len(emails), 100):
|
|
235
|
+
out.extend(self._c.request("POST", "/emails/batch", [_normalize(e) for e in emails[i : i + 100]])["data"])
|
|
236
|
+
return out
|
|
237
|
+
|
|
238
|
+
def get(self, id: str) -> Dict[str, Any]:
|
|
239
|
+
return self._c.request("GET", f"/emails/{_q_id(id)}")
|
|
240
|
+
|
|
241
|
+
def list(self, limit: Optional[int] = None, offset: Optional[int] = None, status: Optional[str] = None) -> Dict[str, Any]:
|
|
242
|
+
return self._c.request("GET", "/emails" + _q(limit=limit, offset=offset, status=status))
|
|
243
|
+
|
|
244
|
+
def all(self, status: Optional[str] = None) -> Iterator[Dict[str, Any]]:
|
|
245
|
+
return _everything(lambda off: self.list(limit=100, offset=off, status=status))
|
|
246
|
+
|
|
247
|
+
def cancel(self, id: str) -> Dict[str, Any]:
|
|
248
|
+
return self._c.request("POST", f"/emails/{_q_id(id)}/cancel", {})
|
|
249
|
+
|
|
250
|
+
def used(self, id: str, request: Any = None, **details: Any) -> Dict[str, Any]:
|
|
251
|
+
"""The person used what the email carried (typed the code). Pass the incoming request."""
|
|
252
|
+
body = requested_from(request) if request is not None and _looks_like_request(request) else dict(request or {})
|
|
253
|
+
body.update(details)
|
|
254
|
+
return self._c.request("POST", f"/emails/{_q_id(id)}/used", body)
|
|
255
|
+
|
|
256
|
+
def wait_for(self, id: str, status: Union[str, List[str]] = "delivered", timeout: float = 60, every: float = 2) -> Dict[str, Any]:
|
|
257
|
+
want = {status} if isinstance(status, str) else set(status)
|
|
258
|
+
end = time.monotonic() + timeout
|
|
259
|
+
while True:
|
|
260
|
+
e = self.get(id)
|
|
261
|
+
if e["status"] in want or e["status"] in ("failed", "bounced", "canceled") or time.monotonic() > end:
|
|
262
|
+
return e
|
|
263
|
+
time.sleep(every)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
class _Domains:
|
|
267
|
+
def __init__(self, c: Receive):
|
|
268
|
+
self._c = c
|
|
269
|
+
|
|
270
|
+
def create(self, name: str):
|
|
271
|
+
return self._c.request("POST", "/domains", {"name": name})
|
|
272
|
+
|
|
273
|
+
def list(self):
|
|
274
|
+
return self._c.request("GET", "/domains")["data"]
|
|
275
|
+
|
|
276
|
+
def get(self, id: str):
|
|
277
|
+
return self._c.request("GET", f"/domains/{_q_id(id)}")
|
|
278
|
+
|
|
279
|
+
def verify(self, id: str):
|
|
280
|
+
return self._c.request("POST", f"/domains/{_q_id(id)}", {})
|
|
281
|
+
|
|
282
|
+
def remove(self, id: str):
|
|
283
|
+
return self._c.request("DELETE", f"/domains/{_q_id(id)}")
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class _Audiences:
|
|
287
|
+
def __init__(self, c: Receive):
|
|
288
|
+
self._c = c
|
|
289
|
+
|
|
290
|
+
def create(self, name: str):
|
|
291
|
+
return self._c.request("POST", "/audiences", {"name": name})
|
|
292
|
+
|
|
293
|
+
def list(self):
|
|
294
|
+
return self._c.request("GET", "/audiences")["data"]
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
class _Contacts:
|
|
298
|
+
def __init__(self, c: Receive):
|
|
299
|
+
self._c = c
|
|
300
|
+
|
|
301
|
+
def create(self, audience_id: str, email: str, first_name: Optional[str] = None, last_name: Optional[str] = None, unsubscribed: Optional[bool] = None):
|
|
302
|
+
body = {k: v for k, v in {"email": email, "first_name": first_name, "last_name": last_name, "unsubscribed": unsubscribed}.items() if v is not None}
|
|
303
|
+
return self._c.request("POST", f"/audiences/{_q_id(audience_id)}/contacts", body)
|
|
304
|
+
|
|
305
|
+
def list(self, audience_id: str, limit: Optional[int] = None, offset: Optional[int] = None):
|
|
306
|
+
return self._c.request("GET", f"/audiences/{_q_id(audience_id)}/contacts" + _q(limit=limit, offset=offset))
|
|
307
|
+
|
|
308
|
+
def all(self, audience_id: str):
|
|
309
|
+
return _everything(lambda off: self.list(audience_id, limit=100, offset=off))
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class _Suppressions:
|
|
313
|
+
def __init__(self, c: Receive):
|
|
314
|
+
self._c = c
|
|
315
|
+
|
|
316
|
+
def add(self, email: str, detail: Optional[str] = None):
|
|
317
|
+
return self._c.request("POST", "/suppressions", {"email": email, **({"detail": detail} if detail else {})})
|
|
318
|
+
|
|
319
|
+
def remove(self, email: str):
|
|
320
|
+
return self._c.request("DELETE", "/suppressions" + _q(email=email))
|
|
321
|
+
|
|
322
|
+
def list(self, limit: Optional[int] = None, offset: Optional[int] = None):
|
|
323
|
+
return self._c.request("GET", "/suppressions" + _q(limit=limit, offset=offset))
|
|
324
|
+
|
|
325
|
+
def all(self):
|
|
326
|
+
return _everything(lambda off: self.list(limit=100, offset=off))
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
class _Webhooks:
|
|
330
|
+
_SIG = re.compile(r"t=(\d+),v1=([0-9a-fA-F]+)")
|
|
331
|
+
|
|
332
|
+
def verify(self, raw_body: Union[str, bytes], signature: Optional[str], secret: str, tolerance: int = 300) -> Dict[str, Any]:
|
|
333
|
+
"""Checks a webhook really came from Receive and returns the event. Raises ReceiveError if not.
|
|
334
|
+
Pass the raw body (Flask: request.get_data(), Django: request.body)."""
|
|
335
|
+
body = raw_body.decode() if isinstance(raw_body, (bytes, bytearray)) else raw_body
|
|
336
|
+
m = self._SIG.search(signature or "")
|
|
337
|
+
|
|
338
|
+
def bad(why: str) -> ReceiveError:
|
|
339
|
+
return ReceiveError(f"Webhook signature check failed: {why}", "invalid_signature", 400)
|
|
340
|
+
|
|
341
|
+
if not m:
|
|
342
|
+
raise bad("no Receive-Signature header.")
|
|
343
|
+
if abs(time.time() - int(m.group(1))) > tolerance:
|
|
344
|
+
raise bad("the call is too old (possible replay).")
|
|
345
|
+
expected = hmac.new(secret.encode(), f"{m.group(1)}.{body}".encode(), hashlib.sha256).hexdigest()
|
|
346
|
+
if not hmac.compare_digest(expected, m.group(2).lower()):
|
|
347
|
+
raise bad("the signature does not match. Check the secret, and pass the raw body.")
|
|
348
|
+
return json.loads(body)
|
|
349
|
+
|
|
350
|
+
def is_valid(self, raw_body: Union[str, bytes], signature: Optional[str], secret: str) -> bool:
|
|
351
|
+
try:
|
|
352
|
+
self.verify(raw_body, signature, secret)
|
|
353
|
+
return True
|
|
354
|
+
except ReceiveError:
|
|
355
|
+
return False
|
|
356
|
+
|
|
357
|
+
def sign(self, raw_body: str, secret: str, t: Optional[int] = None) -> str:
|
|
358
|
+
t = t or int(time.time())
|
|
359
|
+
return f"t={t},v1=" + hmac.new(secret.encode(), f"{t}.{raw_body}".encode(), hashlib.sha256).hexdigest()
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: receive-pk
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: The official Receive SDK: send email, track who read it, verify webhooks. No dependencies.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://receive.pk/docs/sdks/python
|
|
7
|
+
Keywords: email,transactional email,otp,receive,webhooks
|
|
8
|
+
Requires-Python: >=3.8
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# receive_pk
|
|
12
|
+
|
|
13
|
+
The official [Receive](https://receive.pk) SDK for Python.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { Receive } from "receive_pk";
|
|
17
|
+
|
|
18
|
+
const receive = new Receive(process.env.RECEIVE_API_KEY);
|
|
19
|
+
const { data, error } = await receive.emails.send({
|
|
20
|
+
from: "Acme <hello@mail.acme.com>",
|
|
21
|
+
to: "ava@example.com",
|
|
22
|
+
subject: "Welcome",
|
|
23
|
+
html: "<p>Thanks for joining.</p>",
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Zero dependencies. Safe retries, automatic pacing, any-size batches, request-aware `requestedFrom`, and one-line webhook checks.
|
|
28
|
+
|
|
29
|
+
Full guide: https://receive.pk/docs/sdks/python
|
|
30
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
receive_pk
|