sooner-email 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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"]
sooner_email/client.py ADDED
@@ -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
sooner_email/py.typed ADDED
File without changes
sooner_email/types.py ADDED
@@ -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,9 @@
1
+ sooner_email/__init__.py,sha256=BFV0llbENldBRtrMM-1uNQKNMecF6xilsQcV0crOEE0,350
2
+ sooner_email/client.py,sha256=UFy1miDHfSZs-aD_IyeHfxX8M5o6xQVMT6JNfrYTw4c,7224
3
+ sooner_email/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ sooner_email/types.py,sha256=fMxw5_sEl_iY1_IBOLe-2kzHBrd0u0wH9xrcW8T_Y5g,1563
5
+ sooner_email-0.1.0.dist-info/licenses/LICENSE,sha256=SW5H6PQTblzbnjI7qexJNt0fZuKkCOTYqptbwkP7BJM,1063
6
+ sooner_email-0.1.0.dist-info/METADATA,sha256=OlA_EL3-tFx8zqgSfnCi5bV8CMw5MQOkdo_IHESd8dE,3264
7
+ sooner_email-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
8
+ sooner_email-0.1.0.dist-info/top_level.txt,sha256=Xk2v1gx5Dg7J2M6jSZArbibsFUFmYY3ECZfcZk_sVAQ,13
9
+ sooner_email-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ sooner_email