serversmtp 0.3.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.
serversmtp/__init__.py ADDED
@@ -0,0 +1,194 @@
1
+ """Official Python SDK for the ServerSMTP transactional email API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ import os
8
+ import re
9
+ import uuid
10
+ from dataclasses import dataclass
11
+ from datetime import datetime, timezone
12
+ from typing import Any, Mapping, Optional, Sequence
13
+ from urllib import error as urlerror
14
+ from urllib import parse, request
15
+
16
+ __all__ = ["ServerSMTP", "ServerSMTPError", "Response", "attachment_from_path"]
17
+ __version__ = "0.3.0"
18
+
19
+ _DEFAULT_BASE_URL = "https://api.serversmtp.ro"
20
+ _KEY_PATTERN = re.compile(r"^[a-zA-Z0-9_.:-]{8,200}$")
21
+
22
+
23
+ class ServerSMTPError(Exception):
24
+ """Raised for API errors (type "api_error") and network failures (type "network_error")."""
25
+
26
+ def __init__(self, message: str, status_code: Optional[int] = None, fields: Optional[list] = None,
27
+ request_id: Optional[str] = None, type: str = "api_error") -> None:
28
+ super().__init__(message)
29
+ self.message = message
30
+ self.status_code = status_code
31
+ self.fields = fields or []
32
+ self.request_id = request_id
33
+ self.type = type
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Response:
38
+ data: dict
39
+ status_code: int
40
+ #: The key sent with the request. Reuse it when retrying so the email is never sent twice.
41
+ idempotency_key: Optional[str] = None
42
+
43
+
44
+ class _NoRedirect(request.HTTPRedirectHandler):
45
+ def redirect_request(self, *args, **kwargs): # noqa: D401 - refuse redirects
46
+ return None
47
+
48
+
49
+ def attachment_from_path(path: "os.PathLike[str] | str", filename: Optional[str] = None,
50
+ content_type: Optional[str] = None) -> dict:
51
+ """Read a file into an attachment dict for emails.send(). Up to 10 files, 10 MB in total."""
52
+ with open(path, "rb") as handle:
53
+ data = handle.read()
54
+ attachment = {"filename": filename or os.path.basename(os.fspath(path)),
55
+ "content": base64.b64encode(data).decode("ascii")}
56
+ if content_type:
57
+ attachment["contentType"] = content_type
58
+ return attachment
59
+
60
+
61
+ def _prepare(message: Mapping[str, Any]) -> dict:
62
+ """Copy the message and base64-encode bytes attachment content."""
63
+ body = dict(message)
64
+ if body.get("attachments") is not None:
65
+ files = []
66
+ for item in body["attachments"]:
67
+ item = dict(item)
68
+ content = item.get("content")
69
+ if isinstance(content, (bytes, bytearray, memoryview)):
70
+ item["content"] = base64.b64encode(bytes(content)).decode("ascii")
71
+ elif not isinstance(content, str):
72
+ raise ValueError("attachment content must be bytes or a base64 string")
73
+ files.append(item)
74
+ body["attachments"] = files
75
+ return body
76
+
77
+
78
+ def _key(value: Optional[str]) -> str:
79
+ key = value or "sdk-" + uuid.uuid4().hex
80
+ if not _KEY_PATTERN.match(key):
81
+ raise ValueError("idempotency_key must be 8-200 characters: letters, digits, _ . : -")
82
+ return key
83
+
84
+
85
+ class _Emails:
86
+ def __init__(self, client: "ServerSMTP") -> None:
87
+ self._client = client
88
+
89
+ def send(self, message: Mapping[str, Any], idempotency_key: Optional[str] = None) -> Response:
90
+ """Send one email: from, to, cc, bcc, subject, html, text, replyTo, attachments, or templateId + variables."""
91
+ return self._client._request("POST", "/v1/send", _prepare(message), _key(idempotency_key))
92
+
93
+ def send_batch(self, messages: Sequence[Mapping[str, Any]], idempotency_key: Optional[str] = None) -> Response:
94
+ """Send up to 8 emails in one call."""
95
+ return self._client._request("POST", "/v1/send/batch", {"messages": [_prepare(m) for m in messages]},
96
+ _key(idempotency_key))
97
+
98
+ def schedule(self, message: Mapping[str, Any], idempotency_key: Optional[str] = None) -> Response:
99
+ """Schedule an email up to 30 days ahead. sendAt is a timezone-aware datetime or an ISO 8601 string."""
100
+ body = _prepare(message)
101
+ when = body.get("sendAt")
102
+ if isinstance(when, datetime):
103
+ if when.tzinfo is None:
104
+ raise ValueError("sendAt must be timezone-aware")
105
+ body["sendAt"] = when.astimezone(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
106
+ return self._client._request("POST", "/v1/send/scheduled", body, _key(idempotency_key))
107
+
108
+
109
+ class _Scheduled:
110
+ def __init__(self, client: "ServerSMTP") -> None:
111
+ self._client = client
112
+
113
+ def list(self, limit: Optional[int] = None, offset: Optional[int] = None) -> Response:
114
+ query = parse.urlencode({k: v for k, v in (("limit", limit), ("offset", offset)) if v is not None})
115
+ return self._client._request("GET", "/v1/send/scheduled" + ("?" + query if query else ""))
116
+
117
+ def get(self, id: str) -> Response:
118
+ return self._client._request("GET", "/v1/send/scheduled/" + parse.quote(id, safe=""))
119
+
120
+ def cancel(self, id: str) -> Response:
121
+ return self._client._request("DELETE", "/v1/send/scheduled/" + parse.quote(id, safe=""))
122
+
123
+
124
+ class _Events:
125
+ def __init__(self, client: "ServerSMTP") -> None:
126
+ self._client = client
127
+
128
+ def trigger(self, event: str, email: str, data: Optional[Mapping[str, Any]] = None,
129
+ phone: Optional[str] = None, audience_id: Optional[str] = None) -> Response:
130
+ """Start the automations listening for event (email and SMS steps). data fills {{name}} in the steps."""
131
+ body: dict = {"event": event, "email": email}
132
+ if audience_id:
133
+ body["audience_id"] = audience_id
134
+ if phone and phone.strip():
135
+ body["phone"] = phone
136
+ if data:
137
+ body["data"] = dict(data)
138
+ return self._client._request("POST", "/v1/events", body)
139
+
140
+
141
+ class ServerSMTP:
142
+ """ServerSMTP client. The API key defaults to the SERVERSMTP_API_KEY environment variable."""
143
+
144
+ def __init__(self, api_key: Optional[str] = None, base_url: str = _DEFAULT_BASE_URL, timeout: float = 30) -> None:
145
+ key = api_key or os.environ.get("SERVERSMTP_API_KEY")
146
+ if not key:
147
+ raise ValueError("Missing API key. Pass it to ServerSMTP() or set SERVERSMTP_API_KEY.")
148
+ self._api_key = key
149
+ self._base_url = base_url.rstrip("/")
150
+ self._timeout = timeout
151
+ self._opener = request.build_opener(_NoRedirect)
152
+ self.emails = _Emails(self)
153
+ self.scheduled = _Scheduled(self)
154
+ self.events = _Events(self)
155
+
156
+ def verify_api_key(self) -> Response:
157
+ """Check that the API key is active."""
158
+ return self._request("POST", "/v1/auth/check")
159
+
160
+ def _request(self, method: str, path: str, body: Optional[dict] = None,
161
+ idempotency_key: Optional[str] = None) -> Response:
162
+ headers = {
163
+ "Authorization": "Bearer " + self._api_key,
164
+ "User-Agent": "serversmtp-python/" + __version__,
165
+ "Accept": "application/json",
166
+ }
167
+ data = None
168
+ if body is not None:
169
+ headers["Content-Type"] = "application/json"
170
+ data = json.dumps(body, ensure_ascii=False).encode("utf-8")
171
+ if idempotency_key:
172
+ headers["Idempotency-Key"] = idempotency_key
173
+ req = request.Request(self._base_url + path, data=data, headers=headers, method=method)
174
+ try:
175
+ with self._opener.open(req, timeout=self._timeout) as response:
176
+ return Response(_decode(response.read()), response.status, idempotency_key)
177
+ except urlerror.HTTPError as exc:
178
+ payload = _decode(exc.read())
179
+ raise ServerSMTPError(
180
+ payload.get("message") if isinstance(payload.get("message"), str) else "HTTP %d" % exc.code,
181
+ status_code=exc.code,
182
+ fields=payload.get("fields") if isinstance(payload.get("fields"), list) else [],
183
+ request_id=payload.get("requestId") if isinstance(payload.get("requestId"), str) else None,
184
+ ) from None
185
+ except (urlerror.URLError, TimeoutError, OSError) as exc:
186
+ raise ServerSMTPError(str(getattr(exc, "reason", exc)) or "Network error", type="network_error") from None
187
+
188
+
189
+ def _decode(raw: bytes) -> dict:
190
+ try:
191
+ value = json.loads(raw.decode("utf-8")) if raw else {}
192
+ except ValueError:
193
+ return {}
194
+ return value if isinstance(value, dict) else {}
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: serversmtp
3
+ Version: 0.3.0
4
+ Summary: Official Python SDK for the ServerSMTP transactional email API
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://serversmtp.ro/docs#biblioteci
7
+ Keywords: email,smtp,transactional,serversmtp,amazon-ses,django
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+
11
+ # serversmtp (Python)
12
+
13
+ Official Python SDK for the [ServerSMTP](https://serversmtp.ro) transactional email API. Python 3.9+, standard library only.
14
+
15
+ ```sh
16
+ pip install serversmtp
17
+ ```
18
+
19
+ ```python
20
+ import os
21
+ from serversmtp import ServerSMTP, ServerSMTPError
22
+
23
+ serversmtp = ServerSMTP(os.environ["SERVERSMTP_API_KEY"])
24
+
25
+ response = serversmtp.emails.send(
26
+ {
27
+ "from": "Shop <orders@your-domain.ro>",
28
+ "to": "customer@example.com",
29
+ "subject": "Order #1001 confirmed",
30
+ "html": "<p>Thank you!</p>",
31
+ },
32
+ idempotency_key="order-1001-confirmation",
33
+ )
34
+ print(response.data["status"], response.idempotency_key)
35
+ ```
36
+
37
+ Attachments, CC and BCC (up to 10 files, 10 MB in total; each address counts toward the quota):
38
+
39
+ ```python
40
+ from serversmtp import attachment_from_path
41
+
42
+ serversmtp.emails.send({
43
+ "from": "Shop <orders@your-domain.ro>",
44
+ "to": "customer@example.com",
45
+ "cc": "accounting@your-domain.ro",
46
+ "bcc": ["archive@your-domain.ro"],
47
+ "subject": "Invoice #1001",
48
+ "text": "Your invoice is attached.",
49
+ "attachments": [attachment_from_path("invoice-1001.pdf")],
50
+ })
51
+ ```
52
+
53
+ - `emails.send()`, `emails.send_batch()`, `emails.schedule()` (timezone-aware `datetime` for `sendAt`)
54
+ - `scheduled.list()`, `scheduled.get()`, `scheduled.cancel()`, `verify_api_key()`
55
+ - `events.trigger(event, email, data=None, phone=None, audience_id=None)` starts the automations for an event (email and SMS steps):
56
+
57
+ ```python
58
+ serversmtp.events.trigger("comanda.expediata", "client@example.com",
59
+ {"order_reference": "1001", "tracking_number": "AWB123"}, phone="0722 123 456")
60
+ ```
61
+ - Errors raise `ServerSMTPError` with `status_code`, `fields`, `request_id` and `type`.
62
+
63
+ Docs: https://serversmtp.ro/docs#biblioteci
@@ -0,0 +1,5 @@
1
+ serversmtp/__init__.py,sha256=2o64QrNDLFp6JJLGE5iflbzgY6EyksQh-eAv0JlrGCg,8323
2
+ serversmtp-0.3.0.dist-info/METADATA,sha256=WRGEl_itCU_m9wiFGwCT-h3aDbX-Pm9hRaAlxbhbQPU,2097
3
+ serversmtp-0.3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
4
+ serversmtp-0.3.0.dist-info/top_level.txt,sha256=cgYB9KdgtVCCrSnPDjNL3XyCBic2ad91Wv-J2yLW94Y,11
5
+ serversmtp-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ serversmtp