/** * SendPier Send API — send a stored template. * * Requirements: Node.js 18 or newer. Built-in fetch only, no packages. * * Usage: * export SENDPIER_API_KEY='sp_live_...' * export SENDPIER_DOMAIN='example.com' * export SENDPIER_FROM='orders@example.com' * node send-with-template.mjs 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. */ const API_BASE = 'https://api.sendpier.com'; /** One request to the Send API. */ async function sendpierRequest(method, path, body = null) { const key = process.env.SENDPIER_API_KEY; const domain = process.env.SENDPIER_DOMAIN; if (!key || !domain) { console.error('set SENDPIER_API_KEY and SENDPIER_DOMAIN first'); process.exit(78); } const headers = { Authorization: `Bearer ${key}`, 'X-Domain-Name': domain, Accept: 'application/json', }; if (body !== null) { headers['Content-Type'] = 'application/json'; } const response = await fetch(`${API_BASE}${path}`, { method, headers, body: body === null ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(30_000), }); const raw = await response.text(); let parsed = null; try { parsed = JSON.parse(raw); } catch { // Keep the raw text: status code and body both belong in your log. } return { status: response.status, body: parsed, raw }; } const recipient = process.argv[2]; const templateId = Number.parseInt(process.argv[3] ?? '', 10); const from = process.env.SENDPIER_FROM; if (!recipient || !Number.isInteger(templateId) || templateId <= 0 || !from) { console.error('usage: SENDPIER_FROM=orders@example.com node send-with-template.mjs '); process.exit(64); } const response = await sendpierRequest('POST', '/v1/messages', { from: { email: from }, to: [{ email: recipient }], template_id: templateId, // 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: // variables: { 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. }); console.log(response.raw); if (response.status !== 202) { console.error(`request failed with HTTP ${response.status}`); process.exit(1); } for (const message of response.body?.data ?? []) { console.error(`queued ${message.id} for ${message.to}`); }