#!/usr/bin/env python3 """SendPier Send API — look up one message, or list the most recent ones. Requirements: Python 3.9 or newer. Standard library only, no packages. Usage: export SENDPIER_API_KEY='sp_live_...' export SENDPIER_DOMAIN='example.com' python3 get_message.py # the five most recent messages python3 get_message.py 20 # the twenty most recent messages python3 get_message.py msg_5f1c9a... # one message by its identifier Mind the difference between the two answers: the list returns the internal status of a message, the single lookup returns the public one (queued, delivered, bounced, complained, failed). Compare like with like, or -- better -- let a webhook tell you and stop asking. """ import json import os import sys import urllib.error import urllib.parse import urllib.request API_BASE = "https://api.sendpier.com" def sendpier_get(path, timeout=30): """One GET 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") request = urllib.request.Request( API_BASE + path, headers={ "Authorization": "Bearer " + key, "X-Domain-Name": domain, "Accept": "application/json", }, method="GET", ) 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(): argument = sys.argv[1] if len(sys.argv) > 1 else "5" if argument.startswith("msg_"): # An identifier: ask for exactly that message. status, body, raw = sendpier_get("/v1/messages/" + urllib.parse.quote(argument)) else: # A number: the list endpoint. limit is clamped to 1..20, default 5. limit = int(argument) if argument.isdigit() else 5 status, body, raw = sendpier_get("/v1/messages?limit={}".format(max(1, min(20, limit)))) print(raw) if status != 200: # 404 message_not_found also covers "this identifier belongs to another # domain" -- a key only ever sees its own. sys.exit("request failed with HTTP {}".format(status)) # The single lookup answers one message object, the list answers a # "messages" array. Wrapping the first in a list lets one loop print both. messages = (body or {}).get("messages", [body]) for message in messages: if not isinstance(message, dict): continue print( "{} {:<28} {}".format( message.get("status", "?"), # The single lookup names the recipient "to", the list # "to_email". message.get("to") or message.get("to_email") or "?", message.get("subject", ""), ), file=sys.stderr, ) if __name__ == "__main__": main()