#!/usr/bin/env bash # # SendPier Send API — send a message with a file attached. # # Requirements: bash, curl and base64 (part of GNU coreutils). # # Usage: # export SENDPIER_API_KEY='sp_live_...' # export SENDPIER_DOMAIN='example.com' # export SENDPIER_FROM='invoices@example.com' # ./send-with-attachment.sh 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. Executable file types are refused. set -euo pipefail API_BASE='https://api.sendpier.com' : "${SENDPIER_API_KEY:?set SENDPIER_API_KEY to your Send API key}" : "${SENDPIER_DOMAIN:?set SENDPIER_DOMAIN to the domain the key belongs to}" : "${SENDPIER_FROM:?set SENDPIER_FROM to a sender address on that domain}" recipient="${1:-}" file="${2:-}" if [ -z "$recipient" ] || [ -z "$file" ]; then echo "usage: $0 " >&2 exit 64 fi if [ ! -r "$file" ]; then echo "cannot read ${file}" >&2 exit 66 fi # -w0 keeps the base64 on one line. Line breaks inside the value are allowed as # well, so `base64 "$file"` works too -- this is only about readable output. encoded=$(base64 -w0 "$file") filename=$(basename "$file") # content_type may be left out; it is then derived from the file name. Add a # content_id to turn an attachment into an inline part you can point at from # your HTML with . body=$(cat <Your invoice is attached.

", "attachments": [ { "filename": "${filename}", "content": "${encoded}", "content_type": "application/pdf" } ] } JSON ) response=$(curl -sS -X POST "${API_BASE}/v1/messages" \ -H "Authorization: Bearer ${SENDPIER_API_KEY}" \ -H "X-Domain-Name: ${SENDPIER_DOMAIN}" \ -H 'Content-Type: application/json' \ -H 'Accept: application/json' \ -w '\n%{http_code}' \ -d "$body") status=$(printf '%s' "$response" | tail -n1) payload=$(printf '%s' "$response" | sed '$d') echo "$payload" if [ "$status" != '202' ]; then # 413 message_too_large means the whole message exceeded 25 MB; send big # files as a download link instead. 422 attachment_type_blocked means the # file type never reaches an inbox anyway. echo "request failed with HTTP ${status}" >&2 exit 1 fi echo "accepted (HTTP 202)" >&2