"""Python 3.10+, standard library. One attempt, only after project approval. Sending is disabled at this docs release; production activation is separate. Persist MAILCORE_IDEMPOTENCY_KEY with the application event BEFORE sending. Reuse that key and unchanged payload after an uncertain HTTP result. Save the returned id with the event. Never blindly resend an ambiguous message. """ import json import os import re import sys import urllib.error import urllib.request class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None # Never forward a Bearer key to a redirect destination. def main(): api_key = os.environ.get("MAILCORE_API_KEY", "") key = os.environ.get("MAILCORE_IDEMPOTENCY_KEY", "") if not api_key or "\r" in api_key or "\n" in api_key: raise SystemExit("Set MAILCORE_API_KEY in your server environment") if not re.fullmatch(r"[A-Za-z0-9._:-]{16,128}", key): raise SystemExit("Set the idempotency key saved with this application event") payload = { "from": os.environ.get("MAILCORE_FROM", "Example Shop "), "to": os.environ.get("MAILCORE_TO", "customer@recipient.example"), "subject": "Order #8421 completed", "text": "Your order has been completed.", "tags": {"order_id": "8421"}, } if ".example" in payload["from"] or payload["to"].endswith(".example"): raise SystemExit("Set MAILCORE_FROM to your approved sender and MAILCORE_TO to the recipient") request = urllib.request.Request( "https://mailcore.uz/api/email/v1/emails", data=json.dumps(payload).encode("utf-8"), headers={ "Authorization": "Bearer " + api_key, "Idempotency-Key": key, "Content-Type": "application/json", }, method="POST", ) try: with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response: result = json.loads(response.read(1_048_577)) if response.status != 202: raise ValueError("unexpected HTTP status") print(json.dumps(result)) # Persist id on the business event. except urllib.error.HTTPError as error: try: detail = json.loads(error.read(1_048_577)) except (ValueError, OSError): detail = {"error": "unexpected_http_response"} print(json.dumps({"httpStatus": error.code, **detail}), file=sys.stderr) raise SystemExit(1) except (urllib.error.URLError, TimeoutError, OSError, ValueError): raise SystemExit("No usable HTTP result. Reconcile with the saved event key and unchanged payload.") if __name__ == "__main__": main()