Pigeon

Developer guide

Send email from your app

Pigeon sends your project's transactional email. You make one HTTPS call and the service validates, queues, sends, and tracks delivery. It also skips addresses that have bounced or complained. This guide covers Node.js, Python and Go.

Base URL https://email.example.com
Node.js 18 or later. No dependencies.

Before you start

Ask the service admin for two things:

  1. A project with a verified sending domain, for example billing.example.com. You can send from any address on that domain or its subdomains, and from nothing else.
  2. An API key for that project. It starts with es_live_ and is shown only once, so put it straight into your secret store.

Give your app both values as environment variables:

.env
PIGEON_URL=https://email.example.com
PIGEON_KEY=es_live_xxxxxxxxxxxxxxxxxxxxxxxx

Treat the key like a password. Use it only from server-side code, never from a browser or mobile app. Anyone holding it can send mail as your project.

Set up a client

The API is plain JSON over HTTPS, so you don't need an SDK. Copy this small helper into your project. It adds the key to every request and turns error responses into an exception you can inspect. Every example below uses it.

pigeon.js
const BASE = process.env.PIGEON_URL.replace(/\/+$/, '');
const KEY = process.env.PIGEON_KEY;

export class EmailServiceError extends Error {
  constructor(status, body) {
    super(body?.error?.message ?? `HTTP ${status}`);
    this.status = status;
    this.code = body?.error?.code;
    this.details = body?.error?.details;
  }
}

export async function api(method, path, body) {
  const res = await fetch(BASE + path, {
    method,
    headers: {
      authorization: `Bearer ${KEY}`,
      ...(body !== undefined && { 'content-type': 'application/json' }),
    },
    body: body === undefined ? undefined : JSON.stringify(body),
    signal: AbortSignal.timeout(10_000),
  });
  if (res.status === 204) return null;
  const data = await res.json().catch(() => null);
  if (!res.ok) throw new EmailServiceError(res.status, data);
  return data;
}
shell
pip install requests
pigeon.py
import os

import requests

BASE = os.environ["PIGEON_URL"].rstrip("/")
KEY = os.environ["PIGEON_KEY"]

_session = requests.Session()
_session.headers["Authorization"] = f"Bearer {KEY}"


class EmailServiceError(Exception):
    def __init__(self, status, body):
        err = (body or {}).get("error") or {}
        super().__init__(err.get("message") or f"HTTP {status}")
        self.status = status
        self.code = err.get("code")
        self.details = err.get("details")


def api(method, path, body=None, params=None):
    res = _session.request(method, BASE + path, json=body, params=params, timeout=10)
    if res.status_code == 204:
        return None
    try:
        data = res.json()
    except ValueError:
        data = None
    if not res.ok:
        raise EmailServiceError(res.status_code, data)
    return data
pigeon/client.go
package pigeon

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"time"
)

type Client struct {
	BaseURL string
	APIKey  string
	HTTP    *http.Client
}

// New reads PIGEON_URL and PIGEON_KEY from the environment.
func New() *Client {
	return &Client{
		BaseURL: strings.TrimRight(os.Getenv("PIGEON_URL"), "/"),
		APIKey:  os.Getenv("PIGEON_KEY"),
		HTTP:    &http.Client{Timeout: 10 * time.Second},
	}
}

// APIError is returned for any 4xx or 5xx response.
type APIError struct {
	Status  int             `json:"-"`
	Code    string          `json:"code"`
	Message string          `json:"message"`
	Details json.RawMessage `json:"details,omitempty"`
}

func (e *APIError) Error() string {
	return fmt.Sprintf("email service: %d %s: %s", e.Status, e.Code, e.Message)
}

// Do sends a JSON request. in may be nil; out may be nil to discard the body.
func (c *Client) Do(ctx context.Context, method, path string, in, out any) error {
	var body io.Reader
	if in != nil {
		b, err := json.Marshal(in)
		if err != nil {
			return err
		}
		body = bytes.NewReader(b)
	}
	req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, body)
	if err != nil {
		return err
	}
	req.Header.Set("Authorization", "Bearer "+c.APIKey)
	if in != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	resp, err := c.HTTP.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		var e struct {
			Error APIError `json:"error"`
		}
		_ = json.NewDecoder(resp.Body).Decode(&e)
		e.Error.Status = resp.StatusCode
		if e.Error.Message == "" {
			e.Error.Message = http.StatusText(resp.StatusCode)
		}
		return &e.Error
	}
	if out == nil || resp.StatusCode == http.StatusNoContent {
		return nil
	}
	return json.NewDecoder(resp.Body).Decode(out)
}
pigeon/types.go
package pigeon

import (
	"context"
	"time"
)

type SendRequest struct {
	From           string            `json:"from"`
	To             []string          `json:"to"`
	Cc             []string          `json:"cc,omitempty"`
	Bcc            []string          `json:"bcc,omitempty"`
	ReplyTo        []string          `json:"reply_to,omitempty"`
	Subject        string            `json:"subject,omitempty"`
	HTML           string            `json:"html,omitempty"`
	Text           string            `json:"text,omitempty"`
	Template       string            `json:"template,omitempty"`
	TemplateData   map[string]any    `json:"template_data,omitempty"`
	Headers        map[string]string `json:"headers,omitempty"`
	Tags           map[string]string `json:"tags,omitempty"`
	Attachments    []Attachment      `json:"attachments,omitempty"`
	IdempotencyKey string            `json:"idempotency_key,omitempty"`
}

// Content is a []byte, which encoding/json sends as base64: exactly what the API expects.
type Attachment struct {
	Filename    string `json:"filename"`
	Content     []byte `json:"content"`
	ContentType string `json:"content_type,omitempty"`
	ContentID   string `json:"content_id,omitempty"`
}

type Email struct {
	ID                   string            `json:"id"`
	Status               string            `json:"status"`
	From                 string            `json:"from"`
	To                   []string          `json:"to"`
	SuppressedRecipients []string          `json:"suppressed_recipients"`
	Subject              string            `json:"subject"`
	Template             string            `json:"template"`
	Tags                 map[string]string `json:"tags"`
	Attempts             int               `json:"attempts"`
	LastError            string            `json:"last_error"`
	IdempotencyKey       string            `json:"idempotency_key"`
	CreatedAt            time.Time         `json:"created_at"`
	SentAt               *time.Time        `json:"sent_at"`
	IdempotentReplay     bool              `json:"idempotent_replay"`
	// Only on GET /v1/emails/:id. Metadata only: the content is never returned.
	Attachments []struct {
		Filename    string `json:"filename"`
		ContentType string `json:"content_type"`
		ContentID   string `json:"content_id"`
		Size        int    `json:"size"`
	} `json:"attachments,omitempty"`
}

func (c *Client) Send(ctx context.Context, msg SendRequest) (*Email, error) {
	var e Email
	if err := c.Do(ctx, "POST", "/v1/emails", msg, &e); err != nil {
		return nil, err
	}
	return &e, nil
}

func (c *Client) GetEmail(ctx context.Context, id string) (*Email, error) {
	var e Email
	if err := c.Do(ctx, "GET", "/v1/emails/"+id, nil, &e); err != nil {
		return nil, err
	}
	return &e, nil
}

Send an email

POST /v1/emails with a sender, at least one recipient, a subject and an HTML body, a text body, or both. Always send a text part as well when you can: some clients show only text, and spam filters score HTML-only mail worse.

send.js
import { api } from './pigeon.js';

const email = await api('POST', '/v1/emails', {
  from: 'Billing <no-reply@billing.example.com>',
  to: ['ada@customer.com'],
  reply_to: ['support@example.com'],
  subject: 'Your invoice #42',
  html: '<p>Hi Ada, your invoice for €120 is ready.</p>',
  text: 'Hi Ada, your invoice for €120 is ready.',
  tags: { invoice: '42' },
});

console.log(email.id, email.status); // "8f1c…", "queued"
send.py
from pigeon import api

email = api("POST", "/v1/emails", {
    "from": "Billing <no-reply@billing.example.com>",
    "to": ["ada@customer.com"],
    "reply_to": ["support@example.com"],
    "subject": "Your invoice #42",
    "html": "<p>Hi Ada, your invoice for €120 is ready.</p>",
    "text": "Hi Ada, your invoice for €120 is ready.",
    "tags": {"invoice": "42"},
})

print(email["id"], email["status"])  # "8f1c…", "queued"
main.go
package main

import (
	"context"
	"fmt"
	"log"

	"yourapp/pigeon"
)

func main() {
	client := pigeon.New()

	email, err := client.Send(context.Background(), pigeon.SendRequest{
		From:    "Billing <no-reply@billing.example.com>",
		To:      []string{"ada@customer.com"},
		ReplyTo: []string{"support@example.com"},
		Subject: "Your invoice #42",
		HTML:    "<p>Hi Ada, your invoice for €120 is ready.</p>",
		Text:    "Hi Ada, your invoice for €120 is ready.",
		Tags:    map[string]string{"invoice": "42"},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(email.ID, email.Status) // "8f1c…", "queued"
}

Request fields

FieldTypeNotes
fromstringRequired. addr@domain or Name <addr@domain>. The domain must be one of your project's verified domains or a subdomain of one.
tostring[]Required. At least one. to, cc and bcc together may hold at most 50 addresses.
cc, bccstring[]Optional.
reply_tostring[]Optional, up to 10.
subjectstringRequired unless you use a template. With a template, it overrides the template's subject.
html, textstringAt least one is required unless you use a template.
template, template_datastring, objectRender a stored template. See Templates.
tagsobjectUp to 48 string pairs for your own reporting. Keys and values may contain only letters, digits, _ and -. Keys may not start with emailsvc_.
headersobjectExtra headers, such as List-Unsubscribe. You can't set From, To, Bcc, Subject, Return-Path or other routing headers here.
attachmentsobject[]Optional, up to 10 files, 10 MB in total. Each has filename and base64 content. See Attachments.
idempotency_keystringUp to 255 characters. See Retries and idempotency.

Attachments

Add an attachments array to any email, including emails that use a template. Each file needs a filename and its content as a base64 string. The service stores the files with the email and sends them with it. Retries reuse the same files.

send-with-attachment.js
import { readFile } from 'node:fs/promises';
import { api } from './pigeon.js';

const pdf = await readFile('invoice-42.pdf');

const email = await api('POST', '/v1/emails', {
  from: 'Billing <no-reply@billing.example.com>',
  to: ['ada@customer.com'],
  subject: 'Your invoice #42',
  text: 'Hi Ada, your invoice is attached.',
  attachments: [
    { filename: 'invoice-42.pdf', content: pdf.toString('base64') },
  ],
  idempotency_key: 'invoice-42-sent',
});
send_with_attachment.py
import base64
from pigeon import api

with open("invoice-42.pdf", "rb") as f:
    pdf = base64.b64encode(f.read()).decode("ascii")

email = api("POST", "/v1/emails", {
    "from": "Billing <no-reply@billing.example.com>",
    "to": ["ada@customer.com"],
    "subject": "Your invoice #42",
    "text": "Hi Ada, your invoice is attached.",
    "attachments": [
        {"filename": "invoice-42.pdf", "content": pdf},
    ],
    "idempotency_key": "invoice-42-sent",
})
main.go
pdf, err := os.ReadFile("invoice-42.pdf")
if err != nil {
	log.Fatal(err)
}

// Pass the raw bytes: encoding/json turns a []byte into base64 for you.
email, err := client.Send(ctx, pigeon.SendRequest{
	From:    "Billing <no-reply@billing.example.com>",
	To:      []string{"ada@customer.com"},
	Subject: "Your invoice #42",
	Text:    "Hi Ada, your invoice is attached.",
	Attachments: []pigeon.Attachment{
		{Filename: "invoice-42.pdf", Content: pdf},
	},
	IdempotencyKey: "invoice-42-sent",
})

Attachment fields

FieldTypeNotes
filenamestringRequired. The name the recipient sees, up to 255 characters, with no slashes.
contentstringRequired. The file's bytes, base64-encoded. Send plain base64, not a data: URI. Line breaks in the base64 are fine.
content_typestringOptional MIME type, such as application/pdf. If you leave it out, the service guesses from the file extension for common types (PDF, images, CSV, Office files, ZIP and others) and uses application/octet-stream for everything else.
content_idstringOptional. Makes the file an inline image that your HTML shows with <img src="cid:content_id">. Use letters, digits and . _ @ $ + -, up to 100 characters, unique within the email.

Inline images

To show an image inside the HTML body instead of as a download, give it a content_id and refer to it with cid::

request body
{
  "from": "Billing <no-reply@billing.example.com>",
  "to": ["ada@customer.com"],
  "subject": "Welcome",
  "html": "<img src=\"cid:logo\" alt=\"Acme\"><p>Welcome aboard, Ada.</p>",
  "text": "Welcome aboard, Ada.",
  "attachments": [
    { "filename": "logo.png", "content": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4HyUPAAPUAXnNtuHVAAAAAElFTkSuQmCC", "content_id": "logo" }
  ]
}

Limits

  • Up to 10 files per email.
  • Up to 10 MB in total, measured before base64 encoding. Base64 adds about a third, so the request body can be around 14 MB. For bigger files, upload them somewhere and send a link instead.
  • Executables and scripts can't be sent, because mailbox providers treat them as malware. The blocked extensions are ade adp app asp bas bat cer chm cmd com cpl crt csh der exe fxp gadget hlp hta inf ins isp its js jse ksh lib lnk mad maf mag mam maq mar mas mat mau mav maw mda mdb mde mdt mdw mdz msc msh msh1 msh2 mshxml msh1xml msh2xml msi msp mst ops pcd pif plg prf prg reg scf scr sct shb shs sys ps1 ps1xml ps2 ps2xml psc1 psc2 tmp url vb vbe vbs vps vsmacros vss vst vsw vxd ws wsc wsf wsh xnk. The API rejects these straight away with blocked_attachment_type, so they never get queued. Some mailbox providers also block archives such as .zip that contain executables.

The response from POST /v1/emails doesn't echo attachments. GET /v1/emails/:id lists each file's filename, content_type, content_id and size in bytes, but never the content.

Read the response

The call returns as soon as the email is stored and queued. Sending happens in the background, usually within seconds. A successful call has one of two status codes, and your code should accept both:

  • 202 Accepted: a new email was created.
  • 200 OK with "idempotent_replay": true: an earlier request already used this idempotency_key. You get the original email back, and nothing is sent again.
202 response
{
  "id": "8f1c2a8e-5b7d-4c1e-9a43-2f0c6d1b7e55",
  "status": "queued",
  "from": "Billing <no-reply@billing.example.com>",
  "to": ["ada@customer.com"],
  "cc": [],
  "bcc": [],
  "reply_to": ["support@example.com"],
  "suppressed_recipients": [],
  "subject": "Your invoice #42",
  "template": null,
  "tags": { "invoice": "42" },
  "attempts": 0,
  "last_error": null,
  "idempotency_key": null,
  "created_at": "2026-11-12T09:30:00.000Z",
  "sent_at": null,
  "updated_at": "2026-11-12T09:30:00.000Z",
  "idempotent_replay": false
}

Suppressed recipients

The service keeps a suppression list that all projects share. An address goes on it after a hard bounce or a spam complaint. Suppressed addresses are removed from the email before it is queued, and they are listed in suppressed_recipients. If every to address is suppressed, the status is "suppressed" and nothing is sent. The call still returns success, so check for this case when it matters to you, for example in a password reset flow:

send.js
if (email.status === 'suppressed') {
  // Nothing was sent. Ask the user for another address.
} else if (email.suppressed_recipients.length) {
  console.warn('Skipped suppressed recipients:', email.suppressed_recipients);
}
send.py
if email["status"] == "suppressed":
    # Nothing was sent. Ask the user for another address.
    ...
elif email["suppressed_recipients"]:
    print("Skipped suppressed recipients:", email["suppressed_recipients"])
main.go
if email.Status == "suppressed" {
	// Nothing was sent. Ask the user for another address.
} else if len(email.SuppressedRecipients) > 0 {
	log.Printf("skipped suppressed recipients: %v", email.SuppressedRecipients)
}

Retries and idempotency

If a request times out, you can't tell whether the email was stored. Retrying without protection could send it twice. To prevent that, send an idempotency_key with every email. If the service sees a key again, it returns the email it already stored and sends nothing new.

Keys are remembered for as long as the email is kept: 90 days. After that the email is deleted, and a request reusing its key sends a new email.

The best key comes from the event that triggers the email, such as invoice-42-sent or password-reset-<token id>. A key like that also protects you when a job runs twice or your own process crashes and restarts. If there's no natural key, the helper below makes a random one for each email and reuses it on every retry of that email.

Retry network errors and 5xx responses. Don't retry 4xx responses, because the same request will fail the same way. Add this to the helper file, then use it for every send:

pigeon.js
import { randomUUID } from 'node:crypto';

export async function sendEmail(message, { attempts = 4 } = {}) {
  const body = { idempotency_key: randomUUID(), ...message };
  for (let attempt = 1; ; attempt++) {
    try {
      return await api('POST', '/v1/emails', body);
    } catch (err) {
      const retryable = !(err instanceof EmailServiceError) || err.status >= 500;
      if (!retryable || attempt >= attempts) throw err;
      await new Promise((r) => setTimeout(r, 250 * 2 ** attempt));
    }
  }
}
send.js
import { sendEmail } from './pigeon.js';

await sendEmail({
  from: 'no-reply@billing.example.com',
  to: ['ada@customer.com'],
  subject: 'Your invoice #42',
  text: 'Hi Ada, your invoice is ready.',
  idempotency_key: 'invoice-42-sent',
});
pigeon.py
import time
import uuid


def send_email(message, attempts=4):
    body = {"idempotency_key": str(uuid.uuid4()), **message}
    for attempt in range(1, attempts + 1):
        try:
            return api("POST", "/v1/emails", body)
        except EmailServiceError as err:
            if err.status < 500 or attempt == attempts:
                raise
        except requests.RequestException:
            if attempt == attempts:
                raise
        time.sleep(0.25 * 2 ** attempt)
send.py
from pigeon import send_email

send_email({
    "from": "no-reply@billing.example.com",
    "to": ["ada@customer.com"],
    "subject": "Your invoice #42",
    "text": "Hi Ada, your invoice is ready.",
    "idempotency_key": "invoice-42-sent",
})
pigeon/retry.go
package pigeon

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"errors"
	"time"
)

// SendWithRetry retries network errors and 5xx responses. It reuses one
// idempotency key across attempts, so the email is sent at most once.
func (c *Client) SendWithRetry(ctx context.Context, msg SendRequest, attempts int) (*Email, error) {
	if msg.IdempotencyKey == "" {
		b := make([]byte, 16)
		if _, err := rand.Read(b); err != nil {
			return nil, err
		}
		msg.IdempotencyKey = hex.EncodeToString(b)
	}
	var lastErr error
	for attempt := 1; attempt <= attempts; attempt++ {
		email, err := c.Send(ctx, msg)
		if err == nil {
			return email, nil
		}
		var apiErr *APIError
		if errors.As(err, &apiErr) && apiErr.Status < 500 {
			return nil, err // a 4xx won't succeed on retry
		}
		lastErr = err
		if attempt < attempts {
			select {
			case <-time.After(250 * time.Millisecond << attempt):
			case <-ctx.Done():
				return nil, ctx.Err()
			}
		}
	}
	return nil, lastErr
}

Templates

You can store a template once and then send it by name with different data each time. Templates use Handlebars. In the HTML body, {{name}} is HTML-escaped. Use {{{name}}} only for HTML you trust. Templates belong to your project, and PUT creates a template or replaces the existing one.

templates.js
import { api, sendEmail } from './pigeon.js';

// Create or update (run once, e.g. from a deploy script)
await api('PUT', '/v1/templates/invoice', {
  subject: 'Your invoice #{{number}}',
  html: '<p>Hi {{name}}, invoice {{number}} for {{amount}} is ready.</p>',
  text: 'Hi {{name}}, invoice {{number}} for {{amount}} is ready.',
});

// Preview without sending
const preview = await api('POST', '/v1/templates/invoice/render', {
  data: { name: 'Ada', number: 42, amount: '€120' },
});
console.log(preview.subject); // "Your invoice #42"

// Send it
await sendEmail({
  from: 'no-reply@billing.example.com',
  to: ['ada@customer.com'],
  template: 'invoice',
  template_data: { name: 'Ada', number: 42, amount: '€120' },
  idempotency_key: 'invoice-42-sent',
});
templates.py
from pigeon import api, send_email

# Create or update (run once, e.g. from a deploy script)
api("PUT", "/v1/templates/invoice", {
    "subject": "Your invoice #{{number}}",
    "html": "<p>Hi {{name}}, invoice {{number}} for {{amount}} is ready.</p>",
    "text": "Hi {{name}}, invoice {{number}} for {{amount}} is ready.",
})

# Preview without sending
preview = api("POST", "/v1/templates/invoice/render", {
    "data": {"name": "Ada", "number": 42, "amount": "€120"},
})
print(preview["subject"])  # "Your invoice #42"

# Send it
send_email({
    "from": "no-reply@billing.example.com",
    "to": ["ada@customer.com"],
    "template": "invoice",
    "template_data": {"name": "Ada", "number": 42, "amount": "€120"},
    "idempotency_key": "invoice-42-sent",
})
main.go
ctx := context.Background()

// Create or update (run once, e.g. from a deploy script)
err := client.Do(ctx, "PUT", "/v1/templates/invoice", map[string]string{
	"subject": "Your invoice #{{number}}",
	"html":    "<p>Hi {{name}}, invoice {{number}} for {{amount}} is ready.</p>",
	"text":    "Hi {{name}}, invoice {{number}} for {{amount}} is ready.",
}, nil)
if err != nil {
	log.Fatal(err)
}

data := map[string]any{"name": "Ada", "number": 42, "amount": "€120"}

// Preview without sending
var preview struct{ Subject, HTML, Text string }
err = client.Do(ctx, "POST", "/v1/templates/invoice/render", map[string]any{"data": data}, &preview)
if err != nil {
	log.Fatal(err)
}
fmt.Println(preview.Subject) // "Your invoice #42"

// Send it
_, err = client.SendWithRetry(ctx, pigeon.SendRequest{
	From:           "no-reply@billing.example.com",
	To:             []string{"ada@customer.com"},
	Template:       "invoice",
	TemplateData:   data,
	IdempotencyKey: "invoice-42-sent",
}, 4)
if err != nil {
	log.Fatal(err)
}

The template is rendered at the moment you send. Editing it later doesn't change emails that are already queued. If the template doesn't exist, the send fails with 404 not_found. A template with a syntax error is refused when you save it, with 400 template_syntax. You can also call GET /v1/templates to list your templates, and GET or DELETE /v1/templates/:name to read or remove one.

Track delivery

Each email moves through these statuses:

queued → sending → sent → delivered | bounced | complained ↘ failed rejected for sending, or every retry failed suppressed every "to" address was suppressed; nothing sent

Emails are kept for 90 days, with their delivery events and attachments, and then deleted. After that, GET /v1/emails/:id returns 404. If you need a longer record, store the id and status in your own database.

sent means the email has left the service on its way to the recipient. delivered, bounced and complained come later, when the recipient's mail server reports back. That can take seconds or, for a soft bounce, much longer. Your project doesn't get a callback when the status changes. To find out, fetch the email by its id:

status.js
const email = await api('GET', `/v1/emails/${id}`);
console.log(email.status, email.attempts, email.last_error);

// Delivery events: Delivery, Bounce, Complaint, …
const { data: events } = await api('GET', `/v1/emails/${id}/events`);
for (const e of events) console.log(e.created_at, e.event_type);
status.py
email = api("GET", f"/v1/emails/{email_id}")
print(email["status"], email["attempts"], email["last_error"])

# Delivery events: Delivery, Bounce, Complaint, …
for e in api("GET", f"/v1/emails/{email_id}/events")["data"]:
    print(e["created_at"], e["event_type"])
main.go
email, err := client.GetEmail(ctx, id)
if err != nil {
	log.Fatal(err)
}
fmt.Println(email.Status, email.Attempts, email.LastError)

// Delivery events: Delivery, Bounce, Complaint, …
var events struct {
	Data []struct {
		EventType string         `json:"event_type"`
		Details   map[string]any `json:"details"`
		CreatedAt time.Time      `json:"created_at"`
	} `json:"data"`
}
if err := client.Do(ctx, "GET", "/v1/emails/"+id+"/events", nil, &events); err != nil {
	log.Fatal(err)
}
for _, e := range events.Data {
	fmt.Println(e.CreatedAt, e.EventType)
}

Each event has an event_type, a created_at time and a details object:

event_typedetails
SendEmpty. The email was handed off for delivery.
Deliveryrecipients: the addresses whose mail server accepted it.
DeliveryDelaydelay_type and recipients. Delivery is being retried.
Bouncebounce_type (permanent, transient or undetermined), bounce_subtype, and recipients as {email, diagnostic}. A permanent bounce suppresses the address.
Complaintfeedback_type and recipients. The address is suppressed.
Rejectreason. The email was refused before sending.

The single-email response also includes the rendered html, text, headers and template_data, so you can see exactly what was sent, plus an attachments list with each file's name, type and size.

List your emails

GET /v1/emails returns your project's emails, newest first, without their bodies. You can filter by status and to, and set limit from 1 to 200 (default 50). To get the next page, pass the response's next_before back as before. When there are no more pages, next_before is null.

list.js
// Every bounced email, page by page
let before = null;
do {
  const params = new URLSearchParams({ status: 'bounced', limit: '100' });
  if (before) params.set('before', before);
  const page = await api('GET', `/v1/emails?${params}`);
  for (const m of page.data) console.log(m.created_at, m.to.join(', '), m.subject);
  before = page.next_before;
} while (before);
list.py
# Every bounced email, page by page
params = {"status": "bounced", "limit": 100}
while True:
    page = api("GET", "/v1/emails", params=params)
    for m in page["data"]:
        print(m["created_at"], ", ".join(m["to"]), m["subject"])
    if not page["next_before"]:
        break
    params["before"] = page["next_before"]
main.go
// Every bounced email, page by page
params := url.Values{"status": {"bounced"}, "limit": {"100"}}
for {
	var page struct {
		Data       []pigeon.Email `json:"data"`
		NextBefore *string              `json:"next_before"`
	}
	if err := client.Do(ctx, "GET", "/v1/emails?"+params.Encode(), nil, &page); err != nil {
		log.Fatal(err)
	}
	for _, m := range page.Data {
		fmt.Println(m.CreatedAt, strings.Join(m.To, ", "), m.Subject)
	}
	if page.NextBefore == nil {
		break
	}
	params.Set("before", *page.NextBefore)
}

Suppressions

You don't need to call these endpoints to send safely, because suppressed addresses are skipped automatically. They are useful when you want to check an address before sign-up, or to stop mail to someone who asked you to.

  • GET /v1/suppressions/:email returns {"email": "…", "suppressed": true|false}.
  • POST /v1/suppressions with {"email": "…", "note": "…"} adds a manual suppression and returns 201. The list is shared, so this stops mail to that address from every project.
  • DELETE /v1/suppressions/:email returns 204. You can only remove manual suppressions that your project added. For bounces, complaints and other projects' entries you get 403 suppression_not_removable. Ask an admin to remove those.

The address goes in the URL path, so URL-encode it. Characters that email addresses may contain, such as /, #, ? and %, would otherwise break the URL.

suppressions.js
const path = `/v1/suppressions/${encodeURIComponent(address)}`;

const { suppressed } = await api('GET', path);

await api('POST', '/v1/suppressions', { email: address, note: 'Unsubscribed in settings' });

await api('DELETE', path);
suppressions.py
from urllib.parse import quote

path = f"/v1/suppressions/{quote(address, safe='')}"

suppressed = api("GET", path)["suppressed"]

api("POST", "/v1/suppressions", {"email": address, "note": "Unsubscribed in settings"})

api("DELETE", path)
main.go
path := "/v1/suppressions/" + url.PathEscape(address)

var check struct {
	Suppressed bool `json:"suppressed"`
}
if err := client.Do(ctx, "GET", path, nil, &check); err != nil {
	log.Fatal(err)
}

body := map[string]string{"email": address, "note": "Unsubscribed in settings"}
if err := client.Do(ctx, "POST", "/v1/suppressions", body, nil); err != nil {
	log.Fatal(err)
}

if err := client.Do(ctx, "DELETE", path, nil, nil); err != nil {
	log.Fatal(err) // 403 suppression_not_removable if your project didn't add it
}

Errors

Every error response has the same shape. Branch on code, not on message, because messages may change.

403 response
{
  "error": {
    "code": "sender_domain_not_allowed",
    "message": "Project \"billing\" may not send from \"gmail.com\". Allowed domains: billing.example.com"
  }
}
errors.js
try {
  await sendEmail(message);
} catch (err) {
  if (err instanceof EmailServiceError && err.code === 'invalid_recipient') {
    console.warn('Bad addresses:', err.details.addresses);
  } else {
    throw err;
  }
}
errors.py
try:
    send_email(message)
except EmailServiceError as err:
    if err.code == "invalid_recipient":
        print("Bad addresses:", err.details["addresses"])
    else:
        raise
main.go
_, err = client.SendWithRetry(ctx, msg, 4)
var apiErr *pigeon.APIError
if errors.As(err, &apiErr) && apiErr.Code == "invalid_recipient" {
	log.Printf("bad addresses: %s", apiErr.Details)
} else if err != nil {
	log.Fatal(err)
}
StatusCodeMeaning
400validation_errorThe body doesn't match the schema: a wrong type, a missing field or a value that is too long. details lists each problem.
400invalid_fromfrom isn't a valid address.
400invalid_recipientOne or more of to, cc, bcc or reply_to isn't a valid address. details.addresses lists them.
400missing_recipientNo usable to address.
400too_many_recipientsMore than 50 addresses across to, cc and bcc.
400missing_subject, missing_bodyNo subject, or no html and no text, and no template.
400reserved_header, invalid_headerA header you can't set, or a malformed header name or value.
400invalid_attachmentAn attachment has a bad filename, content_type or content_id, or its content isn't valid base64. details.index says which one.
400blocked_attachment_typeThat file type can't be sent, for example .exe or .js. See Attachments for the full list.
400too_many_attachments, attachments_too_largeMore than 10 files, or more than 10 MB in total before base64 encoding.
400empty_template, template_syntaxThe template renders to nothing, or doesn't compile when you save it.
401unauthorizedThe API key is missing, malformed or revoked.
403sender_domain_not_allowedThe from domain isn't one of your project's domains.
403suppression_not_removableYou tried to remove a suppression your project didn't add.
404not_foundThe email, template or suppression doesn't exist, belongs to another project, or the email is older than 90 days and has been deleted.
5xxinternal_errorA problem on the service's side. Retry with the same idempotency_key.

API reference

Every endpoint needs Authorization: Bearer es_live_…. Request and response bodies are JSON.

MethodPathPurpose
POST/v1/emailsQueue an email. Returns 202, or 200 on an idempotent replay.
GET/v1/emailsList emails. Query: limit, before, status, to.
GET/v1/emails/:idOne email, with its body, attachment metadata, attempts and last error.
GET/v1/emails/:id/eventsDelivery events for the email: delivery, bounce, complaint.
GET/v1/templatesList templates.
GET PUT DELETE/v1/templates/:nameRead, create or replace, or delete a template.
POST/v1/templates/:name/renderPreview a template with {"data": {…}}.
GET/v1/suppressions/:emailCheck whether an address is suppressed.
POST/v1/suppressionsAdd a manual suppression.
DELETE/v1/suppressions/:emailRemove a manual suppression that your project added.