sooner-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.
- sooner_email-0.1.0/LICENSE +21 -0
- sooner_email-0.1.0/PKG-INFO +63 -0
- sooner_email-0.1.0/README.md +47 -0
- sooner_email-0.1.0/pyproject.toml +25 -0
- sooner_email-0.1.0/setup.cfg +4 -0
- sooner_email-0.1.0/src/sooner_email/__init__.py +6 -0
- sooner_email-0.1.0/src/sooner_email/client.py +140 -0
- sooner_email-0.1.0/src/sooner_email/py.typed +0 -0
- sooner_email-0.1.0/src/sooner_email/types.py +71 -0
- sooner_email-0.1.0/src/sooner_email.egg-info/PKG-INFO +63 -0
- sooner_email-0.1.0/src/sooner_email.egg-info/SOURCES.txt +12 -0
- sooner_email-0.1.0/src/sooner_email.egg-info/dependency_links.txt +1 -0
- sooner_email-0.1.0/src/sooner_email.egg-info/top_level.txt +1 -0
- sooner_email-0.1.0/tests/test_client.py +158 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sooner
|
|
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,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sooner-email
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The first-party Python client for the Sooner email API
|
|
5
|
+
Author: Sooner
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://sooner.dev
|
|
8
|
+
Project-URL: Documentation, https://sooner.dev/docs/sdks/python
|
|
9
|
+
Project-URL: Repository, https://github.com/Quad-Labs-LLC/sooner-sdks
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# Sooner Python SDK
|
|
18
|
+
|
|
19
|
+
First-party Python client for sending, listing, retrieving, rescheduling, and canceling Sooner emails. Requires Python 3.11 or newer and has no runtime dependencies.
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
python -m pip install https://github.com/Quad-Labs-LLC/sooner-sdks/releases/download/v0.1.0/sooner_email-0.1.0-py3-none-any.whl
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import os
|
|
27
|
+
from sooner_email import Sooner, SoonerApiError
|
|
28
|
+
|
|
29
|
+
sooner = Sooner(os.environ["SOONER_API_KEY"])
|
|
30
|
+
|
|
31
|
+
try:
|
|
32
|
+
email = sooner.emails.send({
|
|
33
|
+
"from": "Acme <hello@mail.example.com>",
|
|
34
|
+
"to": ["ada@example.com"],
|
|
35
|
+
"subject": "Welcome",
|
|
36
|
+
"text": "Thanks for joining.",
|
|
37
|
+
}, idempotency_key="welcome-user-42")
|
|
38
|
+
print(email["id"])
|
|
39
|
+
except SoonerApiError as error:
|
|
40
|
+
print(error.status, error.code, error.retry_after)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
All fields use the API's snake_case spellings. API keys stay on your server. `base_url` accepts an HTTPS origin, with HTTP permitted for loopback development endpoints. HTTP redirects are rejected to protect the bearer key.
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
sooner.emails.send_batch([
|
|
47
|
+
{"from": "hello@mail.example.com", "to": "ada@example.com", "subject": "Hello", "text": "Hi"},
|
|
48
|
+
], idempotency_key="batch-42")
|
|
49
|
+
page = sooner.emails.list(limit=20)
|
|
50
|
+
email = sooner.emails.get("EMAIL_ID")
|
|
51
|
+
sooner.emails.reschedule("EMAIL_ID", "2026-12-01T09:00:00Z")
|
|
52
|
+
sooner.emails.cancel("EMAIL_ID")
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Management endpoints require a Full access key. Batches reject attachments and scheduling. Sending-domain verification, quotas, message limits, and permissions are enforced by the API.
|
|
56
|
+
|
|
57
|
+
API failures raise `SoonerApiError` with `status`, `code`, and the raw `retry_after` HTTP header. Network failures use status `0` with `network_error` or `timeout`. Malformed or oversized responses raise `invalid_response` or `response_too_large`. Requests are attempted once. A network failure or timeout can happen after acceptance. Retry sends with the original payload and idempotency key to preserve deduplication.
|
|
58
|
+
|
|
59
|
+
`timeout` defaults to 30 seconds and bounds each blocking HTTP operation. A slowly delivered response can take longer than this setting overall. The client caps response bodies at 2 MiB. Use pagination to bound list responses.
|
|
60
|
+
|
|
61
|
+
The SDK is MIT licensed. Its source and release history are maintained in [sooner-sdks](https://github.com/Quad-Labs-LLC/sooner-sdks), with the API guide at [Sooner Python documentation](https://sooner.dev/docs/sdks/python).
|
|
62
|
+
|
|
63
|
+
Run the offline contract checks from this package directory with `PYTHONPATH=src python -m unittest discover -s tests`. Build wheel and source distributions with `python -m build` in a packaging environment that has the build frontend and setuptools installed. The distribution includes inline types and the `py.typed` marker.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Sooner Python SDK
|
|
2
|
+
|
|
3
|
+
First-party Python client for sending, listing, retrieving, rescheduling, and canceling Sooner emails. Requires Python 3.11 or newer and has no runtime dependencies.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
python -m pip install https://github.com/Quad-Labs-LLC/sooner-sdks/releases/download/v0.1.0/sooner_email-0.1.0-py3-none-any.whl
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
import os
|
|
11
|
+
from sooner_email import Sooner, SoonerApiError
|
|
12
|
+
|
|
13
|
+
sooner = Sooner(os.environ["SOONER_API_KEY"])
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
email = sooner.emails.send({
|
|
17
|
+
"from": "Acme <hello@mail.example.com>",
|
|
18
|
+
"to": ["ada@example.com"],
|
|
19
|
+
"subject": "Welcome",
|
|
20
|
+
"text": "Thanks for joining.",
|
|
21
|
+
}, idempotency_key="welcome-user-42")
|
|
22
|
+
print(email["id"])
|
|
23
|
+
except SoonerApiError as error:
|
|
24
|
+
print(error.status, error.code, error.retry_after)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
All fields use the API's snake_case spellings. API keys stay on your server. `base_url` accepts an HTTPS origin, with HTTP permitted for loopback development endpoints. HTTP redirects are rejected to protect the bearer key.
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
sooner.emails.send_batch([
|
|
31
|
+
{"from": "hello@mail.example.com", "to": "ada@example.com", "subject": "Hello", "text": "Hi"},
|
|
32
|
+
], idempotency_key="batch-42")
|
|
33
|
+
page = sooner.emails.list(limit=20)
|
|
34
|
+
email = sooner.emails.get("EMAIL_ID")
|
|
35
|
+
sooner.emails.reschedule("EMAIL_ID", "2026-12-01T09:00:00Z")
|
|
36
|
+
sooner.emails.cancel("EMAIL_ID")
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Management endpoints require a Full access key. Batches reject attachments and scheduling. Sending-domain verification, quotas, message limits, and permissions are enforced by the API.
|
|
40
|
+
|
|
41
|
+
API failures raise `SoonerApiError` with `status`, `code`, and the raw `retry_after` HTTP header. Network failures use status `0` with `network_error` or `timeout`. Malformed or oversized responses raise `invalid_response` or `response_too_large`. Requests are attempted once. A network failure or timeout can happen after acceptance. Retry sends with the original payload and idempotency key to preserve deduplication.
|
|
42
|
+
|
|
43
|
+
`timeout` defaults to 30 seconds and bounds each blocking HTTP operation. A slowly delivered response can take longer than this setting overall. The client caps response bodies at 2 MiB. Use pagination to bound list responses.
|
|
44
|
+
|
|
45
|
+
The SDK is MIT licensed. Its source and release history are maintained in [sooner-sdks](https://github.com/Quad-Labs-LLC/sooner-sdks), with the API guide at [Sooner Python documentation](https://sooner.dev/docs/sdks/python).
|
|
46
|
+
|
|
47
|
+
Run the offline contract checks from this package directory with `PYTHONPATH=src python -m unittest discover -s tests`. Build wheel and source distributions with `python -m build` in a packaging environment that has the build frontend and setuptools installed. The distribution includes inline types and the `py.typed` marker.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sooner-email"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "The first-party Python client for the Sooner email API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.11"
|
|
13
|
+
authors = [{name = "Sooner"}]
|
|
14
|
+
classifiers = ["Programming Language :: Python :: 3", "Typing :: Typed"]
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
Homepage = "https://sooner.dev"
|
|
18
|
+
Documentation = "https://sooner.dev/docs/sdks/python"
|
|
19
|
+
Repository = "https://github.com/Quad-Labs-LLC/sooner-sdks"
|
|
20
|
+
|
|
21
|
+
[tool.setuptools.packages.find]
|
|
22
|
+
where = ["src"]
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.package-data]
|
|
25
|
+
sooner_email = ["py.typed"]
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""First-party Python SDK for the Sooner email API."""
|
|
2
|
+
from .client import Sooner, SoonerApiError
|
|
3
|
+
from .types import Attachment, BatchResult, Email, EmailId, EmailPage, SendEmail, Tag, Template
|
|
4
|
+
|
|
5
|
+
__version__ = "0.1.0"
|
|
6
|
+
__all__ = ["Sooner", "SoonerApiError", "Attachment", "BatchResult", "Email", "EmailId", "EmailPage", "SendEmail", "Tag", "Template"]
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Synchronous, dependency-free HTTP client. Requests are attempted once."""
|
|
2
|
+
import ipaddress
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import re
|
|
6
|
+
import socket
|
|
7
|
+
from http.client import HTTPException
|
|
8
|
+
from urllib.error import HTTPError, URLError
|
|
9
|
+
from urllib.parse import urlencode, urlsplit
|
|
10
|
+
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|
11
|
+
from typing import Any, cast
|
|
12
|
+
|
|
13
|
+
from .types import BatchResult, Email, EmailId, EmailPage, SendEmail
|
|
14
|
+
|
|
15
|
+
MAX_RESPONSE_BYTES = 2 * 1024 * 1024
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SoonerApiError(Exception):
|
|
19
|
+
"""API or transport failure, with machine-readable code and HTTP metadata.
|
|
20
|
+
|
|
21
|
+
A transport failure can occur after the API accepted a write. Reuse the same
|
|
22
|
+
idempotency key when retrying a send or batch.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(self, status: int, code: str, message: str, retry_after: str | None = None):
|
|
26
|
+
super().__init__(message)
|
|
27
|
+
self.status = status
|
|
28
|
+
self.code = code
|
|
29
|
+
self.message = message
|
|
30
|
+
self.retry_after = retry_after
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _NoRedirect(HTTPRedirectHandler):
|
|
34
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _identifier(value: str) -> str:
|
|
39
|
+
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,127}", value):
|
|
40
|
+
raise ValueError("Use a valid email identifier without paths or dot segments")
|
|
41
|
+
return value
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _origin(value: str) -> str:
|
|
45
|
+
if (not isinstance(value, str) or any(ord(char) < 33 for char in value)
|
|
46
|
+
or any(char in value for char in "\\?#")):
|
|
47
|
+
raise ValueError("base_url must be an HTTPS origin or a local loopback HTTP origin")
|
|
48
|
+
parsed = urlsplit(value)
|
|
49
|
+
try:
|
|
50
|
+
local = parsed.hostname == "localhost" or ipaddress.ip_address(parsed.hostname or "").is_loopback
|
|
51
|
+
except ValueError:
|
|
52
|
+
local = False
|
|
53
|
+
if (not parsed.hostname or parsed.username is not None or parsed.password is not None
|
|
54
|
+
or parsed.query or parsed.fragment or parsed.path not in ("", "/")
|
|
55
|
+
or (parsed.scheme != "https" and not (parsed.scheme == "http" and local))):
|
|
56
|
+
raise ValueError("base_url must be an HTTPS origin or a local loopback HTTP origin")
|
|
57
|
+
parsed.port # Validate malformed or out-of-range ports before any I/O.
|
|
58
|
+
return value.rstrip("/")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Emails:
|
|
62
|
+
def __init__(self, client: "Sooner"):
|
|
63
|
+
self._client = client
|
|
64
|
+
|
|
65
|
+
def send(self, payload: SendEmail, *, idempotency_key: str | None = None) -> EmailId:
|
|
66
|
+
return cast(EmailId, self._client._request("POST", "/emails", payload, idempotency_key))
|
|
67
|
+
|
|
68
|
+
def send_batch(self, payload: list[SendEmail], *, idempotency_key: str | None = None) -> BatchResult:
|
|
69
|
+
return cast(BatchResult, self._client._request("POST", "/emails/batch", payload, idempotency_key))
|
|
70
|
+
|
|
71
|
+
def list(self, *, limit: int = 20, after: str | None = None) -> EmailPage:
|
|
72
|
+
if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= 100:
|
|
73
|
+
raise ValueError("limit must be an integer between 1 and 100")
|
|
74
|
+
params: dict[str, str | int] = {"limit": limit}
|
|
75
|
+
if after is not None:
|
|
76
|
+
params["after"] = _identifier(after)
|
|
77
|
+
return cast(EmailPage, self._client._request("GET", "/emails?" + urlencode(params)))
|
|
78
|
+
|
|
79
|
+
def get(self, email_id: str) -> Email:
|
|
80
|
+
return cast(Email, self._client._request("GET", "/emails/" + _identifier(email_id)))
|
|
81
|
+
|
|
82
|
+
def reschedule(self, email_id: str, scheduled_at: str) -> EmailId:
|
|
83
|
+
return cast(EmailId, self._client._request("PATCH", "/emails/" + _identifier(email_id), {"scheduled_at": scheduled_at}))
|
|
84
|
+
|
|
85
|
+
def cancel(self, email_id: str) -> EmailId:
|
|
86
|
+
return cast(EmailId, self._client._request("POST", "/emails/" + _identifier(email_id) + "/cancel"))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class Sooner:
|
|
90
|
+
def __init__(self, api_key: str, *, base_url: str = "https://api.sooner.dev", timeout: float = 30):
|
|
91
|
+
if not isinstance(api_key, str) or not re.fullmatch(r"sn_[A-Za-z0-9_-]{16,200}", api_key):
|
|
92
|
+
raise ValueError("A Sooner API key starting with sn_ is required")
|
|
93
|
+
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not math.isfinite(timeout) or timeout <= 0:
|
|
94
|
+
raise ValueError("timeout must be a finite positive number of seconds")
|
|
95
|
+
self._base_url = _origin(base_url)
|
|
96
|
+
self._api_key = api_key
|
|
97
|
+
self._timeout = timeout
|
|
98
|
+
self._opener = build_opener(_NoRedirect())
|
|
99
|
+
self.emails = Emails(self)
|
|
100
|
+
|
|
101
|
+
def _request(self, method: str, path: str, body: Any = None, idempotency_key: str | None = None) -> dict[str, Any]:
|
|
102
|
+
headers = {"Authorization": "Bearer " + self._api_key, "Accept": "application/json", "User-Agent": "sooner-python/0.1.0"}
|
|
103
|
+
if idempotency_key is not None:
|
|
104
|
+
if not isinstance(idempotency_key, str) or not re.fullmatch(r"[\x20-\x7e]{1,256}", idempotency_key):
|
|
105
|
+
raise ValueError("idempotency_key must contain 1 to 256 printable ASCII characters")
|
|
106
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
107
|
+
data = None
|
|
108
|
+
if body is not None:
|
|
109
|
+
data = json.dumps(body, allow_nan=False).encode("utf-8")
|
|
110
|
+
headers["Content-Type"] = "application/json"
|
|
111
|
+
request = Request(self._base_url + path, data=data, headers=headers, method=method)
|
|
112
|
+
try:
|
|
113
|
+
try:
|
|
114
|
+
response = self._opener.open(request, timeout=self._timeout)
|
|
115
|
+
except HTTPError as error:
|
|
116
|
+
response = error
|
|
117
|
+
with response:
|
|
118
|
+
status = response.status
|
|
119
|
+
retry_after = response.headers.get("Retry-After")
|
|
120
|
+
raw = response.read(MAX_RESPONSE_BYTES + 1)
|
|
121
|
+
if len(raw) > MAX_RESPONSE_BYTES:
|
|
122
|
+
raise SoonerApiError(status, "response_too_large", "Sooner returned an oversized response", retry_after)
|
|
123
|
+
try:
|
|
124
|
+
result = json.loads(raw)
|
|
125
|
+
except (ValueError, UnicodeDecodeError):
|
|
126
|
+
result = None
|
|
127
|
+
if not 200 <= status < 300:
|
|
128
|
+
code = result.get("name") if isinstance(result, dict) else None
|
|
129
|
+
message = result.get("message") if isinstance(result, dict) else None
|
|
130
|
+
raise SoonerApiError(status, code if isinstance(code, str) else "http_error", message if isinstance(message, str) else "Sooner returned an unsuccessful HTTP response", retry_after)
|
|
131
|
+
if not isinstance(result, dict):
|
|
132
|
+
raise SoonerApiError(status, "invalid_response", "Sooner returned an invalid JSON object")
|
|
133
|
+
return result
|
|
134
|
+
except (TimeoutError, socket.timeout):
|
|
135
|
+
raise SoonerApiError(0, "timeout", "Sooner request timed out. A write may have been accepted. Reuse its idempotency key when retrying.") from None
|
|
136
|
+
except URLError as error:
|
|
137
|
+
timeout = isinstance(error.reason, TimeoutError)
|
|
138
|
+
raise SoonerApiError(0, "timeout" if timeout else "network_error", "Sooner request could not complete. A write may have been accepted. Reuse its idempotency key when retrying.") from None
|
|
139
|
+
except (OSError, HTTPException):
|
|
140
|
+
raise SoonerApiError(0, "network_error", "Sooner request could not complete. A write may have been accepted. Reuse its idempotency key when retrying.") from None
|
|
File without changes
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""JSON types accepted and returned by the Sooner emails API."""
|
|
2
|
+
from typing import NotRequired, TypedDict
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class Tag(TypedDict):
|
|
6
|
+
name: str
|
|
7
|
+
value: str
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Attachment(TypedDict, total=False):
|
|
11
|
+
filename: str
|
|
12
|
+
content: str | list[int]
|
|
13
|
+
path: str
|
|
14
|
+
content_type: str
|
|
15
|
+
content_id: str
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Template(TypedDict):
|
|
19
|
+
id: str
|
|
20
|
+
variables: NotRequired[dict[str, str | int | float]]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
SendEmail = TypedDict("SendEmail", {
|
|
24
|
+
"from": NotRequired[str],
|
|
25
|
+
"to": str | list[str],
|
|
26
|
+
"subject": NotRequired[str],
|
|
27
|
+
"html": NotRequired[str],
|
|
28
|
+
"text": NotRequired[str],
|
|
29
|
+
"cc": NotRequired[str | list[str]],
|
|
30
|
+
"bcc": NotRequired[str | list[str]],
|
|
31
|
+
"reply_to": NotRequired[str | list[str]],
|
|
32
|
+
"headers": NotRequired[dict[str, str]],
|
|
33
|
+
"tags": NotRequired[list[Tag]],
|
|
34
|
+
"attachments": NotRequired[list[Attachment]],
|
|
35
|
+
"template": NotRequired[Template],
|
|
36
|
+
"scheduled_at": NotRequired[str],
|
|
37
|
+
"topic_id": NotRequired[str],
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class EmailId(TypedDict):
|
|
42
|
+
id: str
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class BatchResult(TypedDict):
|
|
46
|
+
data: list[EmailId]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
Email = TypedDict("Email", {
|
|
50
|
+
"object": str,
|
|
51
|
+
"id": str,
|
|
52
|
+
"from": str,
|
|
53
|
+
"to": list[str],
|
|
54
|
+
"subject": str,
|
|
55
|
+
"status": str,
|
|
56
|
+
"created_at": str,
|
|
57
|
+
"html": str | None,
|
|
58
|
+
"text": str | None,
|
|
59
|
+
"cc": list[str] | None,
|
|
60
|
+
"bcc": list[str] | None,
|
|
61
|
+
"reply_to": list[str] | None,
|
|
62
|
+
"tags": list[Tag],
|
|
63
|
+
"scheduled_at": str | None,
|
|
64
|
+
"last_event": str,
|
|
65
|
+
"error": NotRequired[str],
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
class EmailPage(TypedDict):
|
|
69
|
+
object: str
|
|
70
|
+
data: list[Email]
|
|
71
|
+
has_more: bool
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sooner-email
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The first-party Python client for the Sooner email API
|
|
5
|
+
Author: Sooner
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://sooner.dev
|
|
8
|
+
Project-URL: Documentation, https://sooner.dev/docs/sdks/python
|
|
9
|
+
Project-URL: Repository, https://github.com/Quad-Labs-LLC/sooner-sdks
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# Sooner Python SDK
|
|
18
|
+
|
|
19
|
+
First-party Python client for sending, listing, retrieving, rescheduling, and canceling Sooner emails. Requires Python 3.11 or newer and has no runtime dependencies.
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
python -m pip install https://github.com/Quad-Labs-LLC/sooner-sdks/releases/download/v0.1.0/sooner_email-0.1.0-py3-none-any.whl
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import os
|
|
27
|
+
from sooner_email import Sooner, SoonerApiError
|
|
28
|
+
|
|
29
|
+
sooner = Sooner(os.environ["SOONER_API_KEY"])
|
|
30
|
+
|
|
31
|
+
try:
|
|
32
|
+
email = sooner.emails.send({
|
|
33
|
+
"from": "Acme <hello@mail.example.com>",
|
|
34
|
+
"to": ["ada@example.com"],
|
|
35
|
+
"subject": "Welcome",
|
|
36
|
+
"text": "Thanks for joining.",
|
|
37
|
+
}, idempotency_key="welcome-user-42")
|
|
38
|
+
print(email["id"])
|
|
39
|
+
except SoonerApiError as error:
|
|
40
|
+
print(error.status, error.code, error.retry_after)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
All fields use the API's snake_case spellings. API keys stay on your server. `base_url` accepts an HTTPS origin, with HTTP permitted for loopback development endpoints. HTTP redirects are rejected to protect the bearer key.
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
sooner.emails.send_batch([
|
|
47
|
+
{"from": "hello@mail.example.com", "to": "ada@example.com", "subject": "Hello", "text": "Hi"},
|
|
48
|
+
], idempotency_key="batch-42")
|
|
49
|
+
page = sooner.emails.list(limit=20)
|
|
50
|
+
email = sooner.emails.get("EMAIL_ID")
|
|
51
|
+
sooner.emails.reschedule("EMAIL_ID", "2026-12-01T09:00:00Z")
|
|
52
|
+
sooner.emails.cancel("EMAIL_ID")
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Management endpoints require a Full access key. Batches reject attachments and scheduling. Sending-domain verification, quotas, message limits, and permissions are enforced by the API.
|
|
56
|
+
|
|
57
|
+
API failures raise `SoonerApiError` with `status`, `code`, and the raw `retry_after` HTTP header. Network failures use status `0` with `network_error` or `timeout`. Malformed or oversized responses raise `invalid_response` or `response_too_large`. Requests are attempted once. A network failure or timeout can happen after acceptance. Retry sends with the original payload and idempotency key to preserve deduplication.
|
|
58
|
+
|
|
59
|
+
`timeout` defaults to 30 seconds and bounds each blocking HTTP operation. A slowly delivered response can take longer than this setting overall. The client caps response bodies at 2 MiB. Use pagination to bound list responses.
|
|
60
|
+
|
|
61
|
+
The SDK is MIT licensed. Its source and release history are maintained in [sooner-sdks](https://github.com/Quad-Labs-LLC/sooner-sdks), with the API guide at [Sooner Python documentation](https://sooner.dev/docs/sdks/python).
|
|
62
|
+
|
|
63
|
+
Run the offline contract checks from this package directory with `PYTHONPATH=src python -m unittest discover -s tests`. Build wheel and source distributions with `python -m build` in a packaging environment that has the build frontend and setuptools installed. The distribution includes inline types and the `py.typed` marker.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/sooner_email/__init__.py
|
|
5
|
+
src/sooner_email/client.py
|
|
6
|
+
src/sooner_email/py.typed
|
|
7
|
+
src/sooner_email/types.py
|
|
8
|
+
src/sooner_email.egg-info/PKG-INFO
|
|
9
|
+
src/sooner_email.egg-info/SOURCES.txt
|
|
10
|
+
src/sooner_email.egg-info/dependency_links.txt
|
|
11
|
+
src/sooner_email.egg-info/top_level.txt
|
|
12
|
+
tests/test_client.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sooner_email
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import json
|
|
3
|
+
import socket
|
|
4
|
+
import unittest
|
|
5
|
+
from email.message import Message
|
|
6
|
+
from http.client import IncompleteRead
|
|
7
|
+
from unittest.mock import patch
|
|
8
|
+
from urllib.error import HTTPError, URLError
|
|
9
|
+
|
|
10
|
+
from sooner_email import Sooner, SoonerApiError
|
|
11
|
+
|
|
12
|
+
KEY = "sn_" + "x" * 32
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Response:
|
|
16
|
+
def __init__(self, body, status=200, headers=None):
|
|
17
|
+
self.status = status
|
|
18
|
+
self.headers = headers or {}
|
|
19
|
+
self.body = body
|
|
20
|
+
|
|
21
|
+
def __enter__(self):
|
|
22
|
+
return self
|
|
23
|
+
|
|
24
|
+
def __exit__(self, *args):
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
def read(self, limit):
|
|
28
|
+
return self.body[:limit]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ClientTests(unittest.TestCase):
|
|
32
|
+
def setUp(self):
|
|
33
|
+
self.client = Sooner(KEY)
|
|
34
|
+
|
|
35
|
+
def test_send_preserves_payload_and_idempotency(self):
|
|
36
|
+
with patch.object(self.client._opener, "open", return_value=Response(b'{"id":"email_1"}')) as opening:
|
|
37
|
+
payload = {"from": "a@example.test", "to": ["b@example.test"], "subject": "Hello", "text": "Hi"}
|
|
38
|
+
self.assertEqual(self.client.emails.send(payload, idempotency_key="order-1"), {"id": "email_1"})
|
|
39
|
+
request = opening.call_args.args[0]
|
|
40
|
+
self.assertEqual(request.full_url, "https://api.sooner.dev/emails")
|
|
41
|
+
self.assertEqual(request.get_method(), "POST")
|
|
42
|
+
self.assertEqual(request.get_header("Idempotency-key"), "order-1")
|
|
43
|
+
self.assertEqual(json.loads(request.data), payload)
|
|
44
|
+
|
|
45
|
+
def test_all_routes(self):
|
|
46
|
+
cases = [
|
|
47
|
+
(lambda: self.client.emails.send_batch([], idempotency_key="batch-1"), "POST", "/emails/batch"),
|
|
48
|
+
(lambda: self.client.emails.list(limit=10, after="email_1"), "GET", "/emails?limit=10&after=email_1"),
|
|
49
|
+
(lambda: self.client.emails.get("email_1"), "GET", "/emails/email_1"),
|
|
50
|
+
(lambda: self.client.emails.reschedule("email_1", "in 1 hour"), "PATCH", "/emails/email_1"),
|
|
51
|
+
(lambda: self.client.emails.cancel("email_1"), "POST", "/emails/email_1/cancel"),
|
|
52
|
+
]
|
|
53
|
+
for operation, method, path in cases:
|
|
54
|
+
with self.subTest(path=path), patch.object(self.client._opener, "open", return_value=Response(b'{}')) as opening:
|
|
55
|
+
operation()
|
|
56
|
+
request = opening.call_args.args[0]
|
|
57
|
+
self.assertEqual(request.get_method(), method)
|
|
58
|
+
self.assertEqual(request.full_url, "https://api.sooner.dev" + path)
|
|
59
|
+
if method == "PATCH":
|
|
60
|
+
self.assertEqual(json.loads(request.data), {"scheduled_at": "in 1 hour"})
|
|
61
|
+
|
|
62
|
+
def test_structured_http_errors(self):
|
|
63
|
+
headers = Message()
|
|
64
|
+
headers["Retry-After"] = "12"
|
|
65
|
+
error = HTTPError("https://api.sooner.dev/emails", 429, "rate limit", headers, io.BytesIO(b'{"name":"rate_limit_exceeded","message":"Wait"}'))
|
|
66
|
+
with patch.object(self.client._opener, "open", side_effect=error), self.assertRaises(SoonerApiError) as caught:
|
|
67
|
+
self.client.emails.send({"to": "b@example.test"})
|
|
68
|
+
self.assertEqual((caught.exception.status, caught.exception.code, caught.exception.retry_after), (429, "rate_limit_exceeded", "12"))
|
|
69
|
+
|
|
70
|
+
def test_redirects_are_not_followed(self):
|
|
71
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
72
|
+
from threading import Thread
|
|
73
|
+
|
|
74
|
+
requests = []
|
|
75
|
+
class Handler(BaseHTTPRequestHandler):
|
|
76
|
+
def do_POST(self):
|
|
77
|
+
requests.append(self.path)
|
|
78
|
+
self.send_response(307)
|
|
79
|
+
self.send_header("Location", "/redirected")
|
|
80
|
+
self.send_header("Content-Length", "0")
|
|
81
|
+
self.end_headers()
|
|
82
|
+
def log_message(self, *args):
|
|
83
|
+
pass
|
|
84
|
+
|
|
85
|
+
server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
86
|
+
thread = Thread(target=server.serve_forever, daemon=True)
|
|
87
|
+
thread.start()
|
|
88
|
+
try:
|
|
89
|
+
local = Sooner(KEY, base_url=f"http://127.0.0.1:{server.server_port}")
|
|
90
|
+
with self.assertRaises(SoonerApiError) as caught:
|
|
91
|
+
local.emails.send({"to": "b@example.test"})
|
|
92
|
+
self.assertEqual(caught.exception.status, 307)
|
|
93
|
+
self.assertEqual(requests, ["/emails"])
|
|
94
|
+
finally:
|
|
95
|
+
server.shutdown()
|
|
96
|
+
server.server_close()
|
|
97
|
+
thread.join()
|
|
98
|
+
|
|
99
|
+
def test_transport_failure_never_retries(self):
|
|
100
|
+
for failure, code in [
|
|
101
|
+
(socket.timeout(), "timeout"),
|
|
102
|
+
(URLError(socket.timeout()), "timeout"),
|
|
103
|
+
(URLError("unavailable"), "network_error"),
|
|
104
|
+
(IncompleteRead(b"partial"), "network_error"),
|
|
105
|
+
]:
|
|
106
|
+
with self.subTest(code=code), patch.object(self.client._opener, "open", side_effect=failure) as opening:
|
|
107
|
+
with self.assertRaises(SoonerApiError) as caught:
|
|
108
|
+
self.client.emails.send({"to": "b@example.test"}, idempotency_key="same-key")
|
|
109
|
+
self.assertEqual(caught.exception.code, code)
|
|
110
|
+
self.assertEqual(caught.exception.status, 0)
|
|
111
|
+
self.assertEqual(opening.call_count, 1)
|
|
112
|
+
|
|
113
|
+
def test_interrupted_response_has_structured_error(self):
|
|
114
|
+
response = Response(b'')
|
|
115
|
+
with patch.object(self.client._opener, "open", return_value=response):
|
|
116
|
+
with patch.object(response, "read", side_effect=IncompleteRead(b'{"id":')):
|
|
117
|
+
with self.assertRaises(SoonerApiError) as caught:
|
|
118
|
+
self.client.emails.send({"to": "b@example.test"})
|
|
119
|
+
self.assertEqual(caught.exception.code, "network_error")
|
|
120
|
+
self.assertEqual(caught.exception.status, 0)
|
|
121
|
+
|
|
122
|
+
def test_timeout_validation_and_configuration(self):
|
|
123
|
+
for timeout in (0, -1, True, float("inf"), float("nan")):
|
|
124
|
+
with self.subTest(timeout=timeout), self.assertRaises(ValueError):
|
|
125
|
+
Sooner(KEY, timeout=timeout)
|
|
126
|
+
client = Sooner(KEY, timeout=5)
|
|
127
|
+
with patch.object(client._opener, "open", return_value=Response(b'{"id":"e"}')) as opening:
|
|
128
|
+
client.emails.get("e")
|
|
129
|
+
self.assertEqual(opening.call_args.kwargs["timeout"], 5)
|
|
130
|
+
|
|
131
|
+
def test_invalid_and_oversized_responses(self):
|
|
132
|
+
for body, code in [(b'<html>Oops</html>', "invalid_response"), (b'[]', "invalid_response"), (b'x' * (2 * 1024 * 1024 + 1), "response_too_large")]:
|
|
133
|
+
with self.subTest(code=code), patch.object(self.client._opener, "open", return_value=Response(body)):
|
|
134
|
+
with self.assertRaises(SoonerApiError) as caught:
|
|
135
|
+
self.client.emails.get("email_1")
|
|
136
|
+
self.assertEqual(caught.exception.code, code)
|
|
137
|
+
|
|
138
|
+
def test_validation_prevents_network_access(self):
|
|
139
|
+
for origin in [
|
|
140
|
+
"http://example.com", "https://user:pass@example.com", "https://example.com/a",
|
|
141
|
+
"https://example.com?q=x", "https://example.com#x", "file:///tmp/key",
|
|
142
|
+
"https://example.com?", "https://example.com#", "https://example.com\\other",
|
|
143
|
+
"https://example.com:99999", "https://example.com\n", "http://127.0.0.1.example.com",
|
|
144
|
+
]:
|
|
145
|
+
with self.subTest(origin=origin), self.assertRaises(ValueError):
|
|
146
|
+
Sooner(KEY, base_url=origin)
|
|
147
|
+
for value in ["../outside", "a/b", "a?b", "", "%2f"]:
|
|
148
|
+
with self.subTest(identifier=value), self.assertRaises(ValueError):
|
|
149
|
+
self.client.emails.get(value)
|
|
150
|
+
for limit in [True, 0, 101, 1.5]:
|
|
151
|
+
with self.subTest(limit=limit), self.assertRaises(ValueError):
|
|
152
|
+
self.client.emails.list(limit=limit)
|
|
153
|
+
with self.assertRaises(ValueError):
|
|
154
|
+
self.client.emails.send({"to": "x@example.test"}, idempotency_key="x\r\nAuthorization: bad")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
if __name__ == "__main__":
|
|
158
|
+
unittest.main()
|