#!/usr/bin/env python3 """SendPier Send API — send a stored template. Requirements: Python 3.9 or newer. Standard library only, no packages. Usage: export SENDPIER_API_KEY='sp_live_...' export SENDPIER_DOMAIN='example.com' export SENDPIER_FROM='orders@example.com' python3 send_with_template.py recipient@example.org 7 The template lives in the control panel; the request only carries its id and the variables. Prefer this over building HTML yourself whenever the values come from your own users: template values are inserted as text, so they cannot break your markup open. """ 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. 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, "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: 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 "" template_id = int(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2].isdigit() else 0 sender = os.environ.get("SENDPIER_FROM", "") if not recipient or template_id <= 0 or not sender: sys.exit( "usage: SENDPIER_FROM=orders@example.com " "python3 send_with_template.py " ) status, body, raw = sendpier_request( "POST", "/v1/messages", { "from": {"email": sender}, "to": [{"email": recipient}], "template_id": template_id, # Send every variable the template uses. Miss one and the whole # request is refused with 422 missing_template_variables, naming the # fields you left out -- so nobody receives a half-filled message. # # Values under an email address apply to that recipient only and win # from the general ones: # {"ordernummer": "A-1", "jan@example.org": {"voornaam": "Jan"}} "variables": { "voornaam": "Jan", "ordernummer": "A-1024", }, # "html" or "text" next to a template_id is refused with 422 # template_body_conflict: the body comes from the template. Your own # "subject" is allowed and overrides the one of the template. }, ) print(raw) if status != 202: sys.exit("request failed with HTTP {}".format(status)) for message in (body or {}).get("data", []): print("queued {} for {}".format(message.get("id"), message.get("to")), file=sys.stderr) if __name__ == "__main__": main()