#!/usr/bin/env python3 """SendPier Send API — send a message with a file attached. 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='invoices@example.com' python3 send_with_attachment.py recipient@example.org ./invoice.pdf Message text, HTML and attachments together may be 25 MB after decoding, and a message carries at most 20 attachments. If one attachment is refused the whole message is refused -- half a mail never goes out. """ import base64 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=120): """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 sendpier_attachment(path, content_type=None, content_id=None): """One entry of the attachments list. `content_type` may be left out; it is then derived from the file name. Add a `content_id` to turn the file into an inline part, and point at it from your HTML with ``. """ with open(path, "rb") as handle: contents = handle.read() attachment = { # Only the file name travels; a path in front of it is cut off anyway. "filename": os.path.basename(path), "content": base64.b64encode(contents).decode("ascii"), } if content_type is not None: attachment["content_type"] = content_type if content_id is not None: attachment["content_id"] = content_id return attachment def main(): recipient = sys.argv[1] if len(sys.argv) > 1 else "" path = sys.argv[2] if len(sys.argv) > 2 else "" sender = os.environ.get("SENDPIER_FROM", "") if not recipient or not path or not sender: sys.exit( "usage: SENDPIER_FROM=invoices@example.com " "python3 send_with_attachment.py " ) status, body, raw = sendpier_request( "POST", "/v1/messages", { "from": {"email": sender, "name": "Example"}, "to": [{"email": recipient}], "subject": "Your invoice", "text": "Your invoice is attached.", "html": "

Your invoice is attached.

", "attachments": [sendpier_attachment(path, "application/pdf")], }, ) print(raw) if status != 202: # 413 message_too_large means the whole message went over 25 MB; send # big files as a download link instead. 422 attachment_type_blocked # means the file type would never reach an inbox anyway -- the last # extension counts, so invoice.pdf.exe is an .exe. 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()