mailko 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.
mailko/__init__.py ADDED
@@ -0,0 +1,68 @@
1
+ """Mailko for Python.
2
+
3
+ ::
4
+
5
+ import mailko
6
+
7
+ client = mailko.Mailko("mk_live_…")
8
+ client.emails.send(
9
+ from_="Tienda <pedidos@tienda.co>",
10
+ to="cliente@correo.com",
11
+ subject="Tu pedido #1234",
12
+ html="<p>Gracias por tu compra</p>",
13
+ )
14
+
15
+ Django: ``EMAIL_BACKEND = "mailko.contrib.django.EmailBackend"`` (see the README).
16
+ """
17
+
18
+ from mailko._version import __version__
19
+ from mailko.client import Mailko
20
+ from mailko.constants import API_VERSION, MARKETING, TRANSACTIONAL
21
+ from mailko.errors import (
22
+ APIConnectionError,
23
+ APIError,
24
+ AuthenticationError,
25
+ BadRequestError,
26
+ ConflictError,
27
+ IdempotencyError,
28
+ MailkoError,
29
+ MessageRejectedError,
30
+ NotFoundError,
31
+ PaymentRequiredError,
32
+ PermissionDeniedError,
33
+ RateLimitError,
34
+ ServerError,
35
+ SignatureVerificationError,
36
+ SuppressedError,
37
+ )
38
+ from mailko.message import Attachment, build_email, check_email
39
+ from mailko.webhooks import construct_event, is_valid_signature, verify_signature
40
+
41
+ __all__ = [
42
+ "API_VERSION",
43
+ "MARKETING",
44
+ "TRANSACTIONAL",
45
+ "APIConnectionError",
46
+ "APIError",
47
+ "Attachment",
48
+ "AuthenticationError",
49
+ "BadRequestError",
50
+ "ConflictError",
51
+ "IdempotencyError",
52
+ "Mailko",
53
+ "MailkoError",
54
+ "MessageRejectedError",
55
+ "NotFoundError",
56
+ "PaymentRequiredError",
57
+ "PermissionDeniedError",
58
+ "RateLimitError",
59
+ "ServerError",
60
+ "SignatureVerificationError",
61
+ "SuppressedError",
62
+ "__version__",
63
+ "build_email",
64
+ "check_email",
65
+ "construct_event",
66
+ "is_valid_signature",
67
+ "verify_signature",
68
+ ]
mailko/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
mailko/client.py ADDED
@@ -0,0 +1,270 @@
1
+ """The HTTP client of Mailko's API ``/v1``.
2
+
3
+ * **One key, one project.** ``mk_live_…`` sends, ``mk_test_…`` validates and
4
+ never delivers; a partner app's key (``mkp_…``) only opens ``client.partner``.
5
+ * **Idempotency.** Every write carries an ``Idempotency-Key`` (a uuid4 unless
6
+ you pass one) and the SAME key on every retry: a retried send never sends
7
+ the email twice.
8
+ * **Retries**, only when retrying is safe and useful: no answer, ``409
9
+ idempotency_key_in_progress``, ``429`` (honouring ``Retry-After`` up to
10
+ ``max_retry_after``; never the month's quota) and ``5xx``. Never another 4xx.
11
+ * Answers are plain ``dict``s, exactly the JSON Mailko returns.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import datetime
17
+ import json as jsonlib
18
+ import platform
19
+ import random
20
+ import time
21
+ import uuid
22
+ from collections.abc import Callable, Iterator, Mapping
23
+ from typing import Any
24
+ from urllib.parse import urlsplit
25
+
26
+ import requests
27
+
28
+ from mailko import resources
29
+ from mailko._version import __version__
30
+ from mailko.constants import (
31
+ API_PREFIX,
32
+ API_VERSION,
33
+ DEFAULT_BASE_URL,
34
+ IDEMPOTENCY_HEADER,
35
+ PARTNER_KEY_PREFIXES,
36
+ PROJECT_KEY_PREFIXES,
37
+ VERSION_HEADER,
38
+ )
39
+ from mailko.errors import APIConnectionError, IdempotencyError, RateLimitError, ServerError, error_from_response
40
+
41
+ #: Network failures after which a request may be retried.
42
+ RETRYABLE_EXCEPTIONS = (
43
+ requests.exceptions.ConnectionError,
44
+ requests.exceptions.Timeout,
45
+ requests.exceptions.ChunkedEncodingError,
46
+ )
47
+ #: A 429 that no wait inside one call can fix.
48
+ NOT_RETRYABLE_429 = frozenset({"monthly_quota_exceeded"})
49
+ WRITE_METHODS = frozenset({"POST", "PATCH", "PUT", "DELETE"})
50
+
51
+
52
+ def _check_key(api_key: str) -> str:
53
+ if not isinstance(api_key, str) or not api_key.strip():
54
+ raise ValueError("Falta la llave de Mailko (mk_live_… o mk_test_…).")
55
+ api_key = api_key.strip()
56
+ if not api_key.startswith(PROJECT_KEY_PREFIXES + PARTNER_KEY_PREFIXES):
57
+ raise ValueError(
58
+ "La llave de Mailko debe empezar por mk_live_ o mk_test_ (o mkp_ si es de una app socia). "
59
+ "Créala en Configuración → Desarrolladores."
60
+ )
61
+ return api_key
62
+
63
+
64
+ def _check_base_url(base_url: str) -> str:
65
+ """https always, except a development host: the key travels in every request."""
66
+ parts = urlsplit(str(base_url).strip())
67
+ host = (parts.hostname or "").lower()
68
+ local = host in ("localhost", "127.0.0.1", "::1") or host.endswith((".localhost", ".test"))
69
+ if not host or parts.scheme not in ("https", "http") or (parts.scheme == "http" and not local):
70
+ raise ValueError(f"base_url debe empezar por https:// (por ejemplo {DEFAULT_BASE_URL}).")
71
+ return str(base_url).strip().rstrip("/")
72
+
73
+
74
+ def _query_value(value: Any) -> str:
75
+ if isinstance(value, bool):
76
+ return "true" if value else "false"
77
+ if isinstance(value, datetime.date | datetime.datetime):
78
+ return value.isoformat()
79
+ return str(value)
80
+
81
+
82
+ def _query(params: Mapping[str, Any] | None) -> dict[str, str]:
83
+ """Query parameters as Mailko reads them: booleans as ``true``/``false``,
84
+ dates in ISO 8601, a list as one comma-separated value (``status=a,b``),
85
+ ``None`` left out."""
86
+ clean: dict[str, str] = {}
87
+ for key, value in (params or {}).items():
88
+ if value is None:
89
+ continue
90
+ if isinstance(value, list | tuple | set | frozenset):
91
+ clean[key] = ",".join(_query_value(item) for item in value)
92
+ else:
93
+ clean[key] = _query_value(value)
94
+ return clean
95
+
96
+
97
+ class Mailko:
98
+ """``Mailko("mk_live_…")``: one client per key, thread-safe for requests.
99
+
100
+ ``client.emails.send(...)``, ``client.domains.list()``… — every resource
101
+ of ``/v1`` hangs from the client."""
102
+
103
+ def __init__(
104
+ self,
105
+ api_key: str,
106
+ *,
107
+ base_url: str = DEFAULT_BASE_URL,
108
+ timeout: float | tuple[float, float] = (5.0, 30.0),
109
+ max_retries: int = 2,
110
+ max_retry_after: float = 10.0,
111
+ session: requests.Session | None = None,
112
+ user_agent: str | None = None,
113
+ ) -> None:
114
+ self.api_key = _check_key(api_key)
115
+ self.livemode = not self.api_key.startswith(("mk_test_", "mkp_test_"))
116
+ self.is_partner = self.api_key.startswith(PARTNER_KEY_PREFIXES)
117
+ self.base_url = _check_base_url(base_url or DEFAULT_BASE_URL)
118
+ if self.base_url.endswith(API_PREFIX):
119
+ self.base_url = self.base_url[: -len(API_PREFIX)]
120
+ self.timeout = timeout
121
+ self.max_retries = max(0, int(max_retries))
122
+ #: A ``Retry-After`` longer than this is not waited for: the error is raised.
123
+ self.max_retry_after = max(0.0, float(max_retry_after))
124
+ self.session = session or requests.Session()
125
+ self.user_agent = user_agent
126
+ self._sleep: Callable[[float], None] = time.sleep
127
+
128
+ self.me = resources.Me(self)
129
+ self.emails = resources.Emails(self)
130
+ self.domains = resources.Domains(self)
131
+ self.suppressions = resources.Suppressions(self)
132
+ self.templates = resources.Templates(self)
133
+ self.usage = resources.Usage(self)
134
+ self.webhook_endpoints = resources.WebhookEndpoints(self)
135
+ self.webhook_events = resources.WebhookEvents(self)
136
+ self.contacts = resources.Contacts(self)
137
+ self.lists = resources.Lists(self)
138
+ self.segments = resources.Segments(self)
139
+ self.campaigns = resources.Campaigns(self)
140
+ self.imports = resources.Imports(self)
141
+ self.partner = resources.Partner(self)
142
+
143
+ def __repr__(self) -> str:
144
+ mode = "live" if self.livemode else "test"
145
+ return f"Mailko(mode={mode!r}, base_url={self.base_url!r})"
146
+
147
+ # -- requests -------------------------------------------------------------
148
+
149
+ def _headers(self, idempotency_key: str | None, *, has_body: bool) -> dict[str, str]:
150
+ agent = f"mailko-python/{__version__} (Python {platform.python_version()})"
151
+ if self.user_agent:
152
+ agent = f"{self.user_agent} {agent}"
153
+ headers = {
154
+ "Authorization": f"Bearer {self.api_key}",
155
+ "Accept": "application/json",
156
+ VERSION_HEADER: API_VERSION,
157
+ "User-Agent": agent,
158
+ }
159
+ if has_body:
160
+ headers["Content-Type"] = "application/json"
161
+ if idempotency_key:
162
+ headers[IDEMPOTENCY_HEADER] = idempotency_key
163
+ return headers
164
+
165
+ @staticmethod
166
+ def _backoff(attempt: int) -> float:
167
+ return min(0.5 * (2**attempt), 8.0) * random.uniform(0.5, 1.0)
168
+
169
+ def request(
170
+ self,
171
+ method: str,
172
+ path: str,
173
+ *,
174
+ params: Mapping[str, Any] | None = None,
175
+ body: Mapping[str, Any] | None = None,
176
+ idempotency_key: str | None = None,
177
+ timeout: float | tuple[float, float] | None = None,
178
+ max_retries: int | None = None,
179
+ ) -> Any:
180
+ """One call to ``/v1{path}``, retried when safe. Answers the JSON
181
+ (``None`` for a 204)."""
182
+ method = method.upper()
183
+ idempotency_key = str(idempotency_key or uuid.uuid4()) if method in WRITE_METHODS else None
184
+ url = f"{self.base_url}{API_PREFIX}{path}"
185
+ data = None
186
+ if body is not None:
187
+ data = jsonlib.dumps(dict(body), separators=(",", ":"), ensure_ascii=False, default=str).encode()
188
+ headers = self._headers(idempotency_key, has_body=data is not None)
189
+ retries = self.max_retries if max_retries is None else max(0, int(max_retries))
190
+ wait = self.timeout if timeout is None else timeout
191
+
192
+ attempt = 0
193
+ while True:
194
+ try:
195
+ # Never follow a redirect: it would turn a POST into a GET
196
+ # (and carry the key wherever it points).
197
+ response = self.session.request(
198
+ method,
199
+ url,
200
+ params=_query(params),
201
+ data=data,
202
+ headers=headers,
203
+ timeout=wait,
204
+ allow_redirects=False,
205
+ )
206
+ except requests.exceptions.SSLError as exc:
207
+ # A bad certificate stays bad: no retry.
208
+ raise APIConnectionError(
209
+ "No se pudo establecer una conexión segura con Mailko (certificado TLS).", code="tls_error"
210
+ ) from exc
211
+ except RETRYABLE_EXCEPTIONS as exc:
212
+ if attempt < retries:
213
+ self._sleep(self._backoff(attempt))
214
+ attempt += 1
215
+ continue
216
+ raise APIConnectionError(
217
+ "Mailko no respondió. Inténtalo de nuevo con la misma idempotency_key.", code="unreachable"
218
+ ) from exc
219
+ except requests.exceptions.RequestException as exc:
220
+ raise APIConnectionError(f"No se pudo llamar a Mailko: {type(exc).__name__}.") from exc
221
+
222
+ if 300 <= response.status_code < 400:
223
+ raise APIConnectionError(
224
+ f"Mailko respondió con una redirección ({response.status_code}). Revisa base_url: "
225
+ f"debe ser la dirección final y con https ({DEFAULT_BASE_URL}).",
226
+ code="redirected",
227
+ )
228
+ if response.status_code < 300:
229
+ if response.status_code == 204 or not response.content:
230
+ return None
231
+ try:
232
+ return response.json()
233
+ except ValueError as exc:
234
+ raise ServerError(
235
+ "Mailko respondió algo que no es JSON.", status=response.status_code, body=response.text
236
+ ) from exc
237
+
238
+ error = error_from_response(response)
239
+ delay = self._retry_delay(error, attempt)
240
+ if attempt < retries and delay is not None:
241
+ self._sleep(delay)
242
+ attempt += 1
243
+ continue
244
+ raise error
245
+
246
+ def _retry_delay(self, error: Exception, attempt: int) -> float | None:
247
+ """Seconds to wait before retrying ``error``, or ``None`` when it
248
+ must be raised now."""
249
+ if isinstance(error, ServerError):
250
+ return self._backoff(attempt)
251
+ if isinstance(error, IdempotencyError) and error.code == "idempotency_key_in_progress":
252
+ return self._backoff(attempt)
253
+ if isinstance(error, RateLimitError) and error.code not in NOT_RETRYABLE_429:
254
+ if error.retry_after is None:
255
+ return self._backoff(attempt)
256
+ if error.retry_after <= self.max_retry_after:
257
+ return error.retry_after
258
+ return None
259
+
260
+ def paginate(self, path: str, params: Mapping[str, Any] | None = None) -> Iterator[dict[str, Any]]:
261
+ """Every item of a paginated list, page after page."""
262
+ query = dict(params or {})
263
+ page = int(query.pop("page", 1) or 1)
264
+ while True:
265
+ answer = self.request("GET", path, params={**query, "page": page}) or {}
266
+ yield from answer.get("data") or []
267
+ pagination = answer.get("pagination") or {}
268
+ if not pagination.get("has_more"):
269
+ return
270
+ page += 1
mailko/constants.py ADDED
@@ -0,0 +1,54 @@
1
+ """What the library knows of Mailko's API ``/v1`` (version ``2026-10-01``).
2
+
3
+ The limits are Mailko's own (``SendEmailSerializer`` and the settings of the
4
+ API): checking them here turns a 4xx into a sentence before the call.
5
+ """
6
+
7
+ DEFAULT_BASE_URL = "https://api.mailko.co"
8
+ API_PREFIX = "/v1"
9
+ API_VERSION = "2026-10-01"
10
+
11
+ IDEMPOTENCY_HEADER = "Idempotency-Key"
12
+ VERSION_HEADER = "Mailko-Version"
13
+ REQUEST_ID_HEADER = "X-Request-Id"
14
+ SIGNATURE_HEADER = "Mailko-Signature"
15
+ EVENT_ID_HEADER = "Mailko-Event-Id"
16
+ EVENT_TYPE_HEADER = "Mailko-Event-Type"
17
+
18
+ #: A project's key (``mk_live_…`` sends, ``mk_test_…`` validates and never
19
+ #: delivers) or a partner app's (``mkp_live_…``, «Conectar Mailko»).
20
+ PROJECT_KEY_PREFIXES = ("mk_live_", "mk_test_")
21
+ PARTNER_KEY_PREFIXES = ("mkp_live_", "mkp_test_")
22
+
23
+ #: The headers a sender may set; Mailko answers any other with 422.
24
+ ALLOWED_HEADERS = frozenset(
25
+ {
26
+ "list-unsubscribe",
27
+ "list-unsubscribe-post",
28
+ "list-id",
29
+ "references",
30
+ "in-reply-to",
31
+ "x-entity-ref-id",
32
+ "precedence",
33
+ }
34
+ )
35
+ #: Recipients of one email, counting «to», «cc» and «bcc».
36
+ MAX_RECIPIENTS = 50
37
+ MAX_ATTACHMENTS = 20
38
+ #: The email's text plus each attachment as base64, as Mailko measures it.
39
+ MAX_MESSAGE_BYTES = 10 * 1000 * 1000
40
+ MAX_TAGS = 10
41
+ MAX_TAG_VALUE = 256
42
+ #: A header line and the subject.
43
+ MAX_LINE = 998
44
+ MAX_CONTENT_TYPE = 100
45
+ MAX_FILENAME = 255
46
+ #: Emails in one ``POST /emails/batch``.
47
+ MAX_BATCH = 100
48
+
49
+ #: Streams of an email.
50
+ TRANSACTIONAL = "transactional"
51
+ MARKETING = "marketing"
52
+
53
+ #: A webhook older than this (seconds) is refused: a captured one replayed.
54
+ WEBHOOK_TOLERANCE_SECONDS = 300
File without changes
@@ -0,0 +1,12 @@
1
+ """Mailko for Django (``pip install "mailko[django]"``).
2
+
3
+ * ``EmailBackend`` — ``EMAIL_BACKEND = "mailko.contrib.django.EmailBackend"``.
4
+ * ``views.webhook_view`` / ``urls`` — the URL for Mailko's webhooks.
5
+ * ``signals.email_event`` / ``signals.webhook_received`` — what to connect to.
6
+
7
+ No models, no migrations: ``INSTALLED_APPS`` needs nothing.
8
+ """
9
+
10
+ from mailko.contrib.django.backend import EmailBackend
11
+
12
+ __all__ = ["EmailBackend"]
@@ -0,0 +1,252 @@
1
+ """Django's email backend over Mailko's API: ``send_mail``, ``EmailMessage``
2
+ and every library that sends through Django go out by ``POST /v1/emails``.
3
+
4
+ ::
5
+
6
+ EMAIL_BACKEND = "mailko.contrib.django.EmailBackend"
7
+ MAILKO_API_KEY = env("MAILKO_API_KEY")
8
+
9
+ One request per message. What Django has becomes the API's fields: the body
10
+ and its HTML alternative, ``cc``, ``bcc``, ``reply_to`` (also a ``Reply-To``
11
+ header), attachments (tuples or MIME parts) and the headers Mailko allows —
12
+ any other header is left out, since Mailko would refuse the whole email.
13
+
14
+ What Django has no word for goes as attributes of the message::
15
+
16
+ message.mailko_tags = {"order": "1234"} # echoed in every webhook
17
+ message.mailko_metadata = {...}
18
+ message.mailko_stream = "marketing" # default: transactional
19
+ message.mailko_template = {"id": "welcome", "variables": {...}}
20
+ message.mailko_idempotency_key = "order-1234-receipt"
21
+
22
+ A stable ``mailko_idempotency_key`` (one per logical email, the same on every
23
+ retry of a task) is what makes a retry safe: Mailko never sends twice under
24
+ one key. After the send, ``message.mailko_id`` and ``message.mailko_status``
25
+ say what Mailko answered.
26
+
27
+ Errors are the library's (``mailko.APIError`` and its subclasses,
28
+ ``MessageRejectedError`` before the call, ``SuppressedError`` when every
29
+ recipient is on the project's suppression list), unless ``fail_silently``.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import logging
35
+ import uuid
36
+ from typing import Any
37
+
38
+ from django.core.mail.backends.base import BaseEmailBackend
39
+
40
+ from mailko.client import Mailko
41
+ from mailko.constants import ALLOWED_HEADERS, MAX_LINE
42
+ from mailko.contrib.django import conf
43
+ from mailko.errors import MailkoError, MessageRejectedError, SuppressedError
44
+ from mailko.message import (
45
+ UNNAMED_ATTACHMENT,
46
+ Attachment,
47
+ address_list,
48
+ bare_address,
49
+ build_email,
50
+ check_email,
51
+ single_line,
52
+ )
53
+
54
+ logger = logging.getLogger("mailko")
55
+
56
+
57
+ def _domain(address: Any) -> str:
58
+ return bare_address(address).rpartition("@")[2]
59
+
60
+
61
+ def _content_of(message: Any) -> tuple[str, str]:
62
+ """``(html, text)``: the body (plain or, with ``content_subtype = "html"``,
63
+ HTML) plus the first alternative of the other kind. Other alternatives
64
+ (``text/calendar``…) have no place in Mailko's API and are left out."""
65
+ html, text = "", ""
66
+ if getattr(message, "content_subtype", "plain") == "html":
67
+ html = message.body or ""
68
+ else:
69
+ text = message.body or ""
70
+ for alternative in getattr(message, "alternatives", None) or ():
71
+ content, mimetype = alternative[0], str(alternative[1] or "").split(";", 1)[0].strip().lower()
72
+ if isinstance(content, bytes):
73
+ content = content.decode("utf-8", "replace")
74
+ if mimetype == "text/html" and not html:
75
+ html = content or ""
76
+ elif mimetype == "text/plain" and not text:
77
+ text = content or ""
78
+ elif mimetype not in ("text/html", "text/plain"):
79
+ logger.warning("Alternative %s left out: Mailko sends only html and text", mimetype)
80
+ return html, text
81
+
82
+
83
+ def _attachment(item: Any) -> Attachment:
84
+ """A Django attachment: a tuple (``EmailAttachment``) or a MIME part."""
85
+ if hasattr(item, "get_content_type"):
86
+ name = item.get_filename() or UNNAMED_ATTACHMENT
87
+ mimetype = item.get_content_type()
88
+ if mimetype == "message/rfc822":
89
+ content = item.get_payload(0).as_bytes()
90
+ else:
91
+ content = item.get_payload(decode=True) or b""
92
+ return Attachment(name, content, mimetype)
93
+ name, content, mimetype = item[0], item[1], item[2] if len(item) > 2 else ""
94
+ return Attachment(name or UNNAMED_ATTACHMENT, content if content is not None else b"", mimetype or "")
95
+
96
+
97
+ def _headers_of(message: Any) -> dict[str, str]:
98
+ allowed = {}
99
+ for name, value in (getattr(message, "extra_headers", None) or {}).items():
100
+ line = single_line(value)
101
+ if str(name).lower() in ALLOWED_HEADERS and line and len(line) <= MAX_LINE:
102
+ allowed[str(name)] = line
103
+ elif str(name).lower() != "reply-to":
104
+ logger.debug("Header %s left out: Mailko does not let a sender set it", name)
105
+ return allowed
106
+
107
+
108
+ def _reply_to(message: Any) -> list[str]:
109
+ reply_to = address_list(getattr(message, "reply_to", None))
110
+ if reply_to:
111
+ return reply_to
112
+ for name, value in (getattr(message, "extra_headers", None) or {}).items():
113
+ if str(name).lower() == "reply-to" and value:
114
+ return [single_line(value)]
115
+ return []
116
+
117
+
118
+ class EmailBackend(BaseEmailBackend):
119
+ """``EMAIL_BACKEND = "mailko.contrib.django.EmailBackend"``, or a mailer
120
+ of ``MAILERS`` (Django 6.1+) whose ``OPTIONS`` may say ``api_key`` and
121
+ ``timeout``. ``api_key=`` overrides ``MAILKO_API_KEY`` for this connection."""
122
+
123
+ def __init__(
124
+ self,
125
+ fail_silently: bool = False,
126
+ *,
127
+ api_key: str | None = None,
128
+ timeout: float | tuple[float, float] | None = None,
129
+ **kwargs: Any,
130
+ ) -> None:
131
+ # Django 6.1 passes ``alias`` (and drops unknown options on its
132
+ # own); older ones take and ignore what they do not know.
133
+ super().__init__(**kwargs)
134
+ # Our own attribute: Django 6.1 deprecates the base class's.
135
+ self.fail_silently = fail_silently
136
+ self.api_key = api_key
137
+ self.timeout = timeout
138
+ self._clients: dict[str, Mailko] = {}
139
+
140
+ # -- what to send ---------------------------------------------------------
141
+
142
+ def message_body(self, message: Any) -> dict[str, Any]:
143
+ """The JSON of ``message`` for ``POST /v1/emails``. Override to add to it."""
144
+ template = getattr(message, "mailko_template", None)
145
+ # A template brings its own content: Mailko refuses both at once.
146
+ html, text = ("", "") if template else _content_of(message)
147
+ body = build_email(
148
+ from_=str(message.from_email or ""),
149
+ to=message.to,
150
+ cc=getattr(message, "cc", None),
151
+ bcc=getattr(message, "bcc", None),
152
+ reply_to=_reply_to(message),
153
+ subject=message.subject or "",
154
+ html=html,
155
+ text=text,
156
+ template=template,
157
+ headers=_headers_of(message),
158
+ attachments=[_attachment(item) for item in getattr(message, "attachments", None) or ()],
159
+ tags=getattr(message, "mailko_tags", None),
160
+ metadata=getattr(message, "mailko_metadata", None),
161
+ stream=getattr(message, "mailko_stream", None),
162
+ )
163
+ if len(body.get("subject") or "") > MAX_LINE:
164
+ body["subject"] = body["subject"][:MAX_LINE]
165
+ return body
166
+
167
+ def api_key_for(self, message: Any) -> str:
168
+ """The key of the project that sends ``message``: the one of its
169
+ sender's domain in ``MAILKO_API_KEYS_BY_DOMAIN``, else ``MAILKO_API_KEY``."""
170
+ if self.api_key:
171
+ return self.api_key
172
+ by_domain = conf.keys_by_domain()
173
+ if by_domain:
174
+ key = by_domain.get(_domain(message.from_email))
175
+ if key:
176
+ return key
177
+ return str(conf.get("MAILKO_API_KEY") or "")
178
+
179
+ def idempotency_key_for(self, message: Any) -> str:
180
+ """The message's ``mailko_idempotency_key`` (the same on every attempt
181
+ of this email, with the same content), or a fresh one."""
182
+ stable = getattr(message, "mailko_idempotency_key", None)
183
+ if stable:
184
+ return str(stable)[:255]
185
+ return str(uuid.uuid4())
186
+
187
+ # -- sending --------------------------------------------------------------
188
+
189
+ def client_for(self, api_key: str) -> Mailko:
190
+ client = self._clients.get(api_key)
191
+ if client is None:
192
+ client = Mailko(
193
+ api_key,
194
+ base_url=conf.get("MAILKO_API_URL"),
195
+ timeout=self.timeout or conf.get("MAILKO_TIMEOUT"),
196
+ max_retries=conf.get("MAILKO_MAX_RETRIES"),
197
+ max_retry_after=conf.get("MAILKO_MAX_RETRY_AFTER"),
198
+ )
199
+ self._clients[api_key] = client
200
+ return client
201
+
202
+ def close(self) -> None:
203
+ for client in self._clients.values():
204
+ client.session.close()
205
+ self._clients = {}
206
+
207
+ def send_messages(self, email_messages: Any) -> int:
208
+ sent = 0
209
+ suppressed: SuppressedError | None = None
210
+ for message in email_messages or ():
211
+ try:
212
+ sent += self._send(message)
213
+ except SuppressedError as exc:
214
+ # Mailko took it and had nobody to send it to: the rest of
215
+ # the batch still goes; it is raised once they did.
216
+ suppressed = suppressed or exc
217
+ except (MailkoError, ValueError):
218
+ # ValueError: a missing or malformed key (Mailko(...) refuses it).
219
+ if not self.fail_silently:
220
+ raise
221
+ if suppressed is not None and not self.fail_silently:
222
+ raise suppressed
223
+ return sent
224
+
225
+ def _send(self, message: Any) -> int:
226
+ if not message.recipients():
227
+ return 0
228
+ if not message.to:
229
+ # Moving a blind copy to «to» would show it to everybody else.
230
+ raise MessageRejectedError(
231
+ "El correo necesita al menos un destinatario en «para»; solo tenía copias.", code="to_required"
232
+ )
233
+ body = self.message_body(message)
234
+ check_email(body)
235
+ api_key = self.api_key_for(message)
236
+ if not api_key:
237
+ raise MessageRejectedError("Falta MAILKO_API_KEY: el envío por Mailko no está configurado.", code="no_key")
238
+ key = self.idempotency_key_for(message)
239
+ # The same key with the same body is answered with the first answer
240
+ # (Mailko replays it); with another body it is an IdempotencyError —
241
+ # never read as «already sent»: it may be another email.
242
+ answer = self.client_for(api_key).emails.send_raw(body, idempotency_key=key) or {}
243
+ message.mailko_id = answer.get("id")
244
+ message.mailko_status = answer.get("status")
245
+ message.mailko_response = answer
246
+ if answer.get("status") == "suppressed":
247
+ raise SuppressedError(
248
+ "No se envió: Mailko tiene bloqueadas todas las direcciones de este correo "
249
+ "(rebotaron o lo marcaron como spam antes).",
250
+ email=answer,
251
+ )
252
+ return 1