serversmtp 0.3.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.
@@ -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,53 @@
1
+ # serversmtp (Python)
2
+
3
+ Official Python SDK for the [ServerSMTP](https://serversmtp.ro) transactional email API. Python 3.9+, standard library only.
4
+
5
+ ```sh
6
+ pip install serversmtp
7
+ ```
8
+
9
+ ```python
10
+ import os
11
+ from serversmtp import ServerSMTP, ServerSMTPError
12
+
13
+ serversmtp = ServerSMTP(os.environ["SERVERSMTP_API_KEY"])
14
+
15
+ response = serversmtp.emails.send(
16
+ {
17
+ "from": "Shop <orders@your-domain.ro>",
18
+ "to": "customer@example.com",
19
+ "subject": "Order #1001 confirmed",
20
+ "html": "<p>Thank you!</p>",
21
+ },
22
+ idempotency_key="order-1001-confirmation",
23
+ )
24
+ print(response.data["status"], response.idempotency_key)
25
+ ```
26
+
27
+ Attachments, CC and BCC (up to 10 files, 10 MB in total; each address counts toward the quota):
28
+
29
+ ```python
30
+ from serversmtp import attachment_from_path
31
+
32
+ serversmtp.emails.send({
33
+ "from": "Shop <orders@your-domain.ro>",
34
+ "to": "customer@example.com",
35
+ "cc": "accounting@your-domain.ro",
36
+ "bcc": ["archive@your-domain.ro"],
37
+ "subject": "Invoice #1001",
38
+ "text": "Your invoice is attached.",
39
+ "attachments": [attachment_from_path("invoice-1001.pdf")],
40
+ })
41
+ ```
42
+
43
+ - `emails.send()`, `emails.send_batch()`, `emails.schedule()` (timezone-aware `datetime` for `sendAt`)
44
+ - `scheduled.list()`, `scheduled.get()`, `scheduled.cancel()`, `verify_api_key()`
45
+ - `events.trigger(event, email, data=None, phone=None, audience_id=None)` starts the automations for an event (email and SMS steps):
46
+
47
+ ```python
48
+ serversmtp.events.trigger("comanda.expediata", "client@example.com",
49
+ {"order_reference": "1001", "tracking_number": "AWB123"}, phone="0722 123 456")
50
+ ```
51
+ - Errors raise `ServerSMTPError` with `status_code`, `fields`, `request_id` and `type`.
52
+
53
+ Docs: https://serversmtp.ro/docs#biblioteci
@@ -0,0 +1,19 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "serversmtp"
7
+ version = "0.3.0"
8
+ description = "Official Python SDK for the ServerSMTP transactional email API"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ keywords = ["email", "smtp", "transactional", "serversmtp", "amazon-ses", "django"]
13
+ dependencies = []
14
+
15
+ [project.urls]
16
+ Homepage = "https://serversmtp.ro/docs#biblioteci"
17
+
18
+ [tool.setuptools.packages.find]
19
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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,8 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/serversmtp/__init__.py
4
+ src/serversmtp.egg-info/PKG-INFO
5
+ src/serversmtp.egg-info/SOURCES.txt
6
+ src/serversmtp.egg-info/dependency_links.txt
7
+ src/serversmtp.egg-info/top_level.txt
8
+ tests/test_client.py
@@ -0,0 +1 @@
1
+ serversmtp
@@ -0,0 +1,137 @@
1
+ """Contract tests. Run: python -m unittest discover -s tests (from sdks/python).
2
+ Starts sdks/contract-server.mjs with Node.js."""
3
+
4
+ import json
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ import unittest
9
+ from datetime import datetime, timedelta, timezone
10
+ from pathlib import Path
11
+ from urllib import request
12
+
13
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
14
+ from serversmtp import ServerSMTP, ServerSMTPError # noqa: E402
15
+
16
+ KEY = "em_live_" + "a" * 48
17
+ MESSAGE = {"from": "Magazin <comenzi@magazin.ro>", "to": "client@example.invalid",
18
+ "subject": "Comanda 1", "html": "<p>Mulțumim</p>"}
19
+
20
+
21
+ class ContractTest(unittest.TestCase):
22
+ @classmethod
23
+ def setUpClass(cls):
24
+ server = Path(__file__).resolve().parents[2] / "contract-server.mjs"
25
+ cls.proc = subprocess.Popen(["node", str(server), "0"], stdout=subprocess.PIPE, text=True)
26
+ port = cls.proc.stdout.readline().split()[-1]
27
+ cls.base = "http://127.0.0.1:" + port
28
+ cls.client = ServerSMTP(KEY, base_url=cls.base, timeout=5)
29
+
30
+ @classmethod
31
+ def tearDownClass(cls):
32
+ cls.proc.terminate()
33
+ cls.proc.wait()
34
+
35
+ def last(self):
36
+ with request.urlopen(self.base + "/__last") as response:
37
+ return json.loads(response.read())
38
+
39
+ def test_send_uses_auth_and_generated_key(self):
40
+ sent = self.client.emails.send(MESSAGE)
41
+ req = self.last()
42
+ self.assertEqual(sent.data["status"], "sent")
43
+ self.assertRegex(sent.idempotency_key, r"^sdk-[0-9a-f]{32}$")
44
+ self.assertEqual(req["headers"]["idempotency-key"], sent.idempotency_key)
45
+ self.assertEqual(req["headers"]["authorization"], "Bearer " + KEY)
46
+ self.assertTrue(req["headers"]["user-agent"].startswith("serversmtp-python/"))
47
+ self.assertEqual(req["body"], MESSAGE)
48
+
49
+ def test_unknown_is_returned_and_key_reused(self):
50
+ res = self.client.emails.send({**MESSAGE, "to": "unknown@example.invalid"}, idempotency_key="order-1001")
51
+ self.assertEqual((res.status_code, res.data["status"], res.idempotency_key), (202, "unknown", "order-1001"))
52
+ self.assertEqual(self.last()["headers"]["idempotency-key"], "order-1001")
53
+ with self.assertRaises(ValueError):
54
+ self.client.emails.send(MESSAGE, idempotency_key="bad key!")
55
+
56
+ def test_errors(self):
57
+ with self.assertRaises(ServerSMTPError) as invalid:
58
+ self.client.emails.send({**MESSAGE, "subject": "invalid"})
59
+ self.assertEqual((invalid.exception.status_code, invalid.exception.fields), (400, ["subject"]))
60
+ with self.assertRaises(ServerSMTPError) as rejected:
61
+ self.client.emails.send({**MESSAGE, "to": "rejected@example.invalid"})
62
+ self.assertEqual((rejected.exception.status_code, rejected.exception.request_id), (502, "req-3"))
63
+ with self.assertRaises(ServerSMTPError) as unauthorized:
64
+ ServerSMTP("em_live_" + "b" * 48, base_url=self.base).verify_api_key()
65
+ self.assertEqual(unauthorized.exception.status_code, 401)
66
+ with self.assertRaises(ServerSMTPError) as offline:
67
+ ServerSMTP(KEY, base_url="http://127.0.0.1:9", timeout=3).emails.send(MESSAGE)
68
+ self.assertEqual(offline.exception.type, "network_error")
69
+
70
+ def test_batch_schedule_and_management(self):
71
+ batch = self.client.emails.send_batch([MESSAGE, {**MESSAGE, "to": "alt@example.invalid"}])
72
+ self.assertEqual(len(batch.data["results"]), 2)
73
+ when = datetime(2030, 1, 1, 11, 0, tzinfo=timezone(timedelta(hours=2)))
74
+ scheduled = self.client.emails.schedule({**MESSAGE, "sendAt": when})
75
+ self.assertEqual(scheduled.status_code, 201)
76
+ self.assertEqual(self.last()["body"]["sendAt"], "2030-01-01T09:00:00.000Z")
77
+ with self.assertRaises(ValueError):
78
+ self.client.emails.schedule({**MESSAGE, "sendAt": datetime(2030, 1, 1)})
79
+ listed = self.client.scheduled.list(limit=10, offset=20)
80
+ self.assertEqual(len(listed.data["items"]), 1)
81
+ self.assertEqual(self.last()["query"], {"limit": "10", "offset": "20"})
82
+ self.assertEqual(self.client.scheduled.get("job-1").data["id"], "job-1")
83
+ self.assertEqual(self.client.scheduled.cancel("job-1").data["status"], "cancelled")
84
+ self.assertEqual(self.last()["method"], "DELETE")
85
+ with self.assertRaises(ServerSMTPError) as missing:
86
+ self.client.scheduled.get("missing")
87
+ self.assertEqual(missing.exception.status_code, 404)
88
+ self.assertEqual(self.client.verify_api_key().data, {"ok": True})
89
+
90
+ def test_cc_bcc_and_attachments(self):
91
+ import base64
92
+ import tempfile
93
+ from serversmtp import attachment_from_path
94
+ with tempfile.TemporaryDirectory() as folder:
95
+ path = Path(folder) / "factura-1001.pdf"
96
+ path.write_bytes(b"%PDF-1.4 fixture")
97
+ from_file = attachment_from_path(path)
98
+ self.assertEqual(from_file, {"filename": "factura-1001.pdf",
99
+ "content": base64.b64encode(b"%PDF-1.4 fixture").decode()})
100
+ self.client.emails.send({**MESSAGE, "cc": "contabil@example.invalid", "bcc": ["arhiva@example.invalid"],
101
+ "attachments": [from_file, {"filename": "nota.txt", "content": "Bună ziua".encode(),
102
+ "contentType": "text/plain"}]})
103
+ body = self.last()["body"]
104
+ self.assertEqual((body["cc"], body["bcc"]), ("contabil@example.invalid", ["arhiva@example.invalid"]))
105
+ self.assertEqual(base64.b64decode(body["attachments"][1]["content"]).decode(), "Bună ziua")
106
+ with self.assertRaises(ValueError):
107
+ self.client.emails.send({**MESSAGE, "attachments": [{"filename": "a.pdf", "content": 42}]})
108
+
109
+ def test_event_trigger(self):
110
+ response = self.client.events.trigger(
111
+ "comanda.expediata", "ana@example.invalid", {"order_reference": "INV-1001"},
112
+ phone="0722 123 456", audience_id="00000000-0000-4000-8000-000000000001")
113
+ self.assertEqual(response.data, {"started": 1})
114
+ req = self.last()
115
+ self.assertEqual(req["path"], "/v1/events")
116
+ self.assertIsNone(req["headers"]["idempotency-key"])
117
+ self.assertEqual(req["body"], {"event": "comanda.expediata", "email": "ana@example.invalid",
118
+ "audience_id": "00000000-0000-4000-8000-000000000001",
119
+ "phone": "0722 123 456", "data": {"order_reference": "INV-1001"}})
120
+ self.client.events.trigger("comanda.platita", "ana@example.invalid", phone=" ")
121
+ self.assertEqual(self.last()["body"], {"event": "comanda.platita", "email": "ana@example.invalid"})
122
+ with self.assertRaises(ServerSMTPError) as ctx:
123
+ self.client.events.trigger("comanda.expediata", "ana@example.invalid", phone="123")
124
+ self.assertEqual(ctx.exception.fields, ["phone"])
125
+
126
+ def test_missing_key(self):
127
+ saved = os.environ.pop("SERVERSMTP_API_KEY", None)
128
+ try:
129
+ with self.assertRaises(ValueError):
130
+ ServerSMTP()
131
+ finally:
132
+ if saved is not None:
133
+ os.environ["SERVERSMTP_API_KEY"] = saved
134
+
135
+
136
+ if __name__ == "__main__":
137
+ unittest.main()