django-serversmtp 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
+ """Django EmailBackend for the ServerSMTP HTTP API."""
2
+
3
+ from .backend import ServerSMTPEmailBackend
4
+
5
+ __all__ = ["ServerSMTPEmailBackend"]
6
+ __version__ = "0.1.0"
@@ -0,0 +1,98 @@
1
+ """Django BaseEmailBackend sending messages through ServerSMTP POST /v1/send."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ from email.mime.base import MIMEBase
7
+ from typing import Any, Iterable, Optional
8
+
9
+ from django.conf import settings
10
+ from django.core.mail.backends.base import BaseEmailBackend
11
+ from serversmtp import ServerSMTP
12
+
13
+
14
+ class ServerSMTPEmailBackend(BaseEmailBackend):
15
+ """Sends Django EmailMessage / EmailMultiAlternatives via the ServerSMTP HTTP API."""
16
+
17
+ def __init__(
18
+ self,
19
+ api_key: Optional[str] = None,
20
+ base_url: Optional[str] = None,
21
+ fail_silently: bool = False,
22
+ **kwargs: Any,
23
+ ) -> None:
24
+ super().__init__(fail_silently=fail_silently, **kwargs)
25
+ key = api_key or getattr(settings, "SERVERSMTP_API_KEY", None)
26
+ url = base_url or getattr(settings, "SERVERSMTP_BASE_URL", "https://api.serversmtp.ro")
27
+ self.client = ServerSMTP(key, base_url=url)
28
+
29
+ @staticmethod
30
+ def build_payload(message: Any) -> tuple[dict[str, Any], Optional[str]]:
31
+ payload: dict[str, Any] = {
32
+ "from": message.from_email,
33
+ "to": list(message.to or []),
34
+ "subject": str(message.subject or ""),
35
+ }
36
+ if getattr(message, "cc", None):
37
+ payload["cc"] = list(message.cc)
38
+ if getattr(message, "bcc", None):
39
+ payload["bcc"] = list(message.bcc)
40
+ if getattr(message, "reply_to", None):
41
+ payload["replyTo"] = message.reply_to[0]
42
+
43
+ html_body = None
44
+ if getattr(message, "content_subtype", "plain") == "html":
45
+ html_body = message.body
46
+ else:
47
+ payload["text"] = message.body or ""
48
+ for content, mimetype in getattr(message, "alternatives", []) or []:
49
+ if mimetype == "text/html":
50
+ html_body = content
51
+ break
52
+ if html_body:
53
+ payload["html"] = html_body
54
+ if not payload.get("html") and not payload.get("text"):
55
+ payload["text"] = " "
56
+
57
+ attachments = []
58
+ for attachment in getattr(message, "attachments", []) or []:
59
+ if isinstance(attachment, MIMEBase):
60
+ raw = attachment.get_payload(decode=True) or b""
61
+ filename = attachment.get_filename() or f"attachment-{len(attachments) + 1}"
62
+ mimetype = attachment.get_content_type() or "application/octet-stream"
63
+ elif isinstance(attachment, (tuple, list)) and len(attachment) >= 2:
64
+ filename, content = attachment[0], attachment[1]
65
+ mimetype = attachment[2] if len(attachment) > 2 and attachment[2] else "application/octet-stream"
66
+ raw = content.encode("utf-8") if isinstance(content, str) else bytes(content)
67
+ else:
68
+ continue
69
+ attachments.append({
70
+ "filename": str(filename),
71
+ "content": base64.b64encode(raw).decode("ascii"),
72
+ "contentType": str(mimetype),
73
+ })
74
+ if attachments:
75
+ payload["attachments"] = attachments
76
+
77
+ headers = getattr(message, "extra_headers", {}) or {}
78
+ idempotency_key = None
79
+ for key, value in headers.items():
80
+ if str(key).lower() == "idempotency-key" and value:
81
+ idempotency_key = str(value).strip()
82
+ break
83
+
84
+ return payload, idempotency_key
85
+
86
+ def send_messages(self, email_messages: Iterable[Any]) -> int:
87
+ sent = 0
88
+ for message in email_messages or []:
89
+ if not getattr(message, "to", None):
90
+ continue
91
+ try:
92
+ payload, key = self.build_payload(message)
93
+ self.client.emails.send(payload, idempotency_key=key)
94
+ sent += 1
95
+ except Exception:
96
+ if not self.fail_silently:
97
+ raise
98
+ return sent
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-serversmtp
3
+ Version: 0.1.0
4
+ Summary: Django EmailBackend for the ServerSMTP HTTP API (POST /v1/send)
5
+ License: MIT
6
+ Project-URL: Documentation, https://serversmtp.ro/docs#biblioteci
7
+ Keywords: django,email,serversmtp,transactional
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ Requires-Dist: serversmtp>=0.3.0
11
+ Requires-Dist: Django>=4.2
12
+
13
+ # django-serversmtp
14
+
15
+ EmailBackend oficial pentru **Django 4.2+** care trimite mesajele `django.core.mail` (`send_mail`, `EmailMessage`, `EmailMultiAlternatives`) prin API-ul HTTP **ServerSMTP** (`POST /v1/send`).
16
+
17
+ ## Configurare (`settings.py`)
18
+
19
+ ```python
20
+ EMAIL_BACKEND = "django_serversmtp.ServerSMTPEmailBackend"
21
+ SERVERSMTP_API_KEY = os.environ["SERVERSMTP_API_KEY"]
22
+ DEFAULT_FROM_EMAIL = "Facturi <facturi@exemplu.invalid>"
23
+ ```
24
+
25
+ ## Trimitere cu atașamente și Idempotency-Key
26
+
27
+ ```python
28
+ from django.core.mail import EmailMultiAlternatives
29
+
30
+ email = EmailMultiAlternatives(
31
+ subject="Factura #1042",
32
+ body="Mulțumim pentru comandă!",
33
+ to=["client@exemplu.invalid"],
34
+ headers={"Idempotency-Key": "factura-1042"},
35
+ )
36
+ email.attach_alternative("<p>Mulțumim pentru comandă!</p>", "text/html")
37
+ email.attach("factura-1042.pdf", pdf_bytes, "application/pdf")
38
+ email.send()
39
+ ```
@@ -0,0 +1,6 @@
1
+ django_serversmtp/__init__.py,sha256=aOAP_sulXA2ZucnEArsOsSNa2LxnWkvtlD_yu2u6_Mg,160
2
+ django_serversmtp/backend.py,sha256=Gnl_7H2JERd3Q-9Ic1zxPH_qvwWRhimS1Hbw8wGp9y4,3918
3
+ django_serversmtp-0.1.0.dist-info/METADATA,sha256=jbV8WKwiBXUHVLfiLP3_h4VVdaPK71Zs9R5VoKBfJ-s,1269
4
+ django_serversmtp-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ django_serversmtp-0.1.0.dist-info/top_level.txt,sha256=hz0oLuHW6dYYG2ZsFqQiC759sueULot0sSQAwq1CKzk,18
6
+ django_serversmtp-0.1.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
+ django_serversmtp