#!/usr/bin/env python3 """SendPier Send API — send a single message. Requirements: Python 3.9 or newer. Standard library only, no packages -- so this runs anywhere, including in a container without pip. Using `requests`? Replace `sendpier_request` with a `requests.post(...)`; the headers and the body stay exactly the same. Usage: export SENDPIER_API_KEY='sp_live_...' # the key of one verified domain export SENDPIER_DOMAIN='example.com' # that same domain export SENDPIER_FROM='noreply@example.com' # must live on that domain python3 send_message.py recipient@example.org A successful call answers 202 Accepted and returns one identifier per recipient. 202 means "accepted for delivery", not "delivered" -- ask get_message.py later, or let a webhook tell you. """ import json import os import sys import urllib.error import urllib.request API_BASE = "https://api.sendpier.com" def sendpier_request(method, path, body=None, timeout=30): """One request to the Send API. Keep the key in the environment or in a secrets store, never in your source and never anywhere a browser can read it: the Send API is meant for traffic from your own server. Returns (status, parsed_body_or_None, raw_text). """ key = os.environ.get("SENDPIER_API_KEY", "") domain = os.environ.get("SENDPIER_DOMAIN", "") if not key or not domain: sys.exit("set SENDPIER_API_KEY and SENDPIER_DOMAIN first") headers = { "Authorization": "Bearer " + key, # Required on every request. The key belongs to one domain and this # header has to name that same domain, or the answer is 403. "X-Domain-Name": domain, "Accept": "application/json", } data = None if body is not None: data = json.dumps(body).encode("utf-8") headers["Content-Type"] = "application/json" request = urllib.request.Request(API_BASE + path, data=data, headers=headers, method=method) try: with urllib.request.urlopen(request, timeout=timeout) as response: status = response.status raw = response.read().decode("utf-8") except urllib.error.HTTPError as error: # A 4xx or 5xx is an answer, not a crash: the body carries the error # code that says what to change. status = error.code raw = error.read().decode("utf-8", "replace") except urllib.error.URLError as error: sys.exit("connection failed: {}".format(error.reason)) try: parsed = json.loads(raw) except ValueError: parsed = None return status, parsed, raw def main(): recipient = sys.argv[1] if len(sys.argv) > 1 else "" sender = os.environ.get("SENDPIER_FROM", "") if not recipient or not sender: sys.exit( "usage: SENDPIER_FROM=noreply@example.com " "python3 send_message.py " ) status, body, raw = sendpier_request( "POST", "/v1/messages", { "from": {"email": sender, "name": "Example"}, # Ten recipients fit in one request, but prefer one: then you know # the status per email and one bad address cannot take the rest # down with it. "to": [{"email": recipient}], "subject": "Hello from the Send API", "text": "This message was sent from Python.", "html": "

This message was sent from Python.

", }, ) print(raw) if status != 202: # Log the status code *and* the body. Retry 429 and 503 with a growing # wait; a 422 will come back in exactly the same way. sys.exit("request failed with HTTP {}".format(status)) for message in (body or {}).get("data", []): # Store this identifier next to your own record: it is what you look # the message up with, and what a webhook reports back to you. print("queued {} for {}".format(message.get("id"), message.get("to")), file=sys.stderr) if __name__ == "__main__": main()