Search by

postilon / postilon-php

murt-widi

PHP SDK for the Postilon transactional email API

v1.0.0 2026-11-25 16:13 UTC

This package is not auto-updated.

Last update: 2026-11-26 14:47:26 UTC


README

PHP client for the Postilon transactional email API. PHP 8.1 or later, no dependencies beyond the curl and json extensions.

Full API documentation: postilon.com/docs.

Install

composer require postilon/postilon-php

Send an email

Create an API key in the dashboard under API Keys, and keep it in an environment variable.

use Postilon\Client;

$postilon = new Client(getenv('POSTILON_API_KEY'));

$email = $postilon->emails->send([
    'from' => 'Acme <hello@acme.com>',
    'to' => 'jane@example.com',
    'subject' => 'Your sign-in code',
    'html' => '<p>Your code is <strong>482913</strong>.</p>',
    'text' => 'Your code is 482913.',
]);
// ['id' => 'msg_…', 'status' => 'queued', …]

Requests are associative arrays with the API's own field names, and every method returns the decoded JSON response as an array. send takes every field of POST /v1/emails: cc, bcc, reply_to, headers, tags, attachments, template_id with variables, scheduled_at and stream.

new Client($key, baseUrl: 'http://localhost:8080') changes the API address. Requests time out after 30 seconds; for another timeout, pass transport: new Postilon\Http\CurlTransport(timeout: 10). Any Postilon\Http\Transport works there, such as a fake in your tests.

Test keys

ps_test_… keys are for development: emails are accepted, rendered and reported like real ones, but nothing is delivered and no credits are used, and any from address works. ps_live_… keys send real mail from a verified domain. The SDK treats both the same.

Idempotency

Pass an idempotency key, such as the order or event ID the email is for, so a retried request never sends twice. It is sent as the Idempotency-Key header:

$postilon->emails->send(
    ['from' => 'billing@acme.com', 'to' => 'jane@example.com', 'subject' => 'Receipt for order #123', 'text' => 'Thanks.'],
    idempotencyKey: 'receipt-order-123',
);

A retry with the same key and body returns the original response. The same key with a different body fails with 409 idempotency_key_reused, so use one key per email.

Resources

Resource Methods
$postilon->emails send($params, idempotencyKey:), sendBatch($params), get($id), list($params), cancel($id)
$postilon->domains create($params), list($params), get($id), verify($id), update($id, $params), delete($id)
$postilon->templates create($params), list($params), get($id), update($id, $params), delete($id)
$postilon->files upload($params), list($params), delete($id)
$postilon->suppressions list($params), create($params), delete($id)
$postilon->webhooks create($params), list($params), get($id), update($id, $params), delete($id), test($id), listEventTypes(), listDeliveries($params), replayDelivery($id), verifySignature(…)
$postilon->inbound list($params), get($id), attachment($id, $index), raw($id)
$postilon->streams list(), create($params), get($name), update($name, $params), delete($name)

Batch, scheduling and cancelling

sendBatch sends up to 100 emails in one request, all or nothing. They share from, subject, html, text and template_id; each item has its own to and variables:

$postilon->emails->sendBatch([
    'from' => 'Acme <hello@acme.com>',
    'template_id' => 'tmpl_…',
    'batch' => [
        ['to' => 'jane@example.com', 'variables' => ['name' => 'Jane']],
        ['to' => 'omar@example.com', 'variables' => ['name' => 'Omar']],
    ],
]);

With scheduled_at in the future ('2026-11-01T09:00:00Z'), an email waits as scheduled. $postilon->emails->cancel($id) cancels a queued or scheduled email and returns its credits; once delivery has started it fails with 409 cannot_cancel.

Streams

Streams keep kinds of email apart, such as receipts and a newsletter, each with its own suppressions. Every workspace has the transactional stream, which cannot be changed or deleted. A stream name is 1 to 32 lowercase letters, digits or hyphens:

$postilon->streams->create(['name' => 'receipts', 'description' => 'Order receipts']);

$postilon->emails->send(['from' => 'billing@acme.com', 'to' => 'jane@example.com', 'subject' => 'Receipt', 'text' => 'Thanks.', 'stream' => 'receipts']);
$postilon->emails->list(['stream' => 'receipts']);

Without stream, an email goes in the API key's stream, or else in transactional; a batch takes one top-level stream for all its emails. A key bound to a stream can send only in it (403 stream_restricted). Emails and webhook events carry their stream. Deleting a stream fails with 409 stream_in_use while an active API key sends in it.

Attachments and files

Attach a file inline, with its content in Base64, or upload it once and refer to it by file_id. Give an image a content_id to show it in the HTML as cid::

$file = $postilon->files->upload([
    'filename' => 'terms.pdf',
    'content_type' => 'application/pdf',
    'content' => base64_encode(file_get_contents('terms.pdf')),
]);

$postilon->emails->send([
    'from' => 'Acme <hello@acme.com>',
    'to' => 'jane@example.com',
    'subject' => 'Welcome',
    'html' => '<img src="cid:logo" alt="Acme"><p>Welcome aboard.</p>',
    'attachments' => [
        ['file_id' => $file['id']],
        ['filename' => 'logo.png', 'content_type' => 'image/png', 'content' => base64_encode(file_get_contents('logo.png')), 'content_id' => 'logo'],
    ],
]);

Domains, templates, suppressions and webhooks

$domain = $postilon->domains->create(['domain_name' => 'acme.com']); // add $domain['dns_records'] at your DNS host
$postilon->domains->verify($domain['id']);

$template = $postilon->templates->create(['name' => 'Welcome', 'subject_template' => 'Hi {{ name }}', 'html_template' => '<p>Hi {{ name }}</p>']);
$postilon->emails->send(['from' => 'hello@acme.com', 'to' => 'jane@example.com', 'template_id' => $template['id'], 'variables' => ['name' => 'Jane']]);

$postilon->suppressions->create(['email_address' => 'jane@example.com']); // every stream
$postilon->suppressions->create(['email_address' => 'omar@example.com', 'reason' => 'unsubscribe', 'stream' => 'newsletter']);

$webhook = $postilon->webhooks->create(['url' => 'https://acme.com/webhooks/postilon', 'subscribed_events' => ['email.bounced', 'email.complained']]);
// $webhook['signing_secret'] is the secret for verifySignature
$deliveries = $postilon->webhooks->listDeliveries(['webhook_id' => $webhook['id']]);
$postilon->webhooks->replayDelivery($deliveries['data'][0]['id']);

Errors

When the API answers with an error, the call throws Postilon\Exception\PostilonException with the HTTP status, the errorCode and the message (list of codes). A network failure or timeout throws the transport's RuntimeException (PostilonException extends RuntimeException too, so catch it first).

use Postilon\Exception\PostilonException;

try {
    $postilon->emails->send(['from' => 'hello@acme.com', 'to' => 'jane@example.com', 'subject' => 'Hi', 'text' => 'Hi']);
} catch (PostilonException $e) {
    if ($e->errorCode === 'rate_limit_exceeded') {
        // $e->rateLimitReset: when the window resets, in Unix seconds (X-RateLimit-Reset)
    } else {
        error_log("$e->status $e->errorCode {$e->getMessage()}"); // 403 domain_not_verified …
    }
}

A workspace can make 100 requests per second; use emails->sendBatch for many emails at once. 429 daily_limit_reached means the daily sending limit is reached, and retrying within the second will not help. Streams add 403 stream_restricted, 409 stream_exists and 409 stream_in_use. An error response that is not JSON (from a proxy, say) gets the code http_error.

Pagination

Lists return ['object' => 'list', 'data', 'count', 'total', 'has_more'] and take limit (default 100, at most 1000) and offset, newest first:

$offset = 0;
do {
    $page = $postilon->emails->list(['status' => 'bounced', 'limit' => 100, 'offset' => $offset]);
    foreach ($page['data'] as $email) {
        echo $email['id'], ' ', implode(', ', $email['to']), "\n";
    }
    $offset += $page['count'];
} while ($page['has_more']);

Verify webhooks

Each webhook request carries X-Postilon-Signature: t=<unix>,v1=<hex>. Verify it against the raw body, before any JSON decoding, with the endpoint's signing secret (whsec_…, returned when the endpoint is created). Signatures older than 5 minutes are refused; change that with toleranceSeconds:.

use Postilon\Webhook;

$body = file_get_contents('php://input');
$header = $_SERVER['HTTP_X_POSTILON_SIGNATURE'] ?? null;

if (!Webhook::verifySignature($body, $header, getenv('POSTILON_WEBHOOK_SECRET'))) {
    http_response_code(400);
    exit;
}

$event = json_decode($body, true);
if ($event['type'] === 'email.bounced') {
    // $event['data']['recipient'] bounced
}
http_response_code(200);

$postilon->webhooks->verifySignature(...) is the same function. Answer with a 2xx within 8 seconds and do slow work afterwards. Events can arrive more than once and out of order, so use the event id to ignore duplicates. See Webhooks.

Receive email

Turn on inbound for a verified domain (or a subdomain of it), and add the MX record it returns:

$domain = $postilon->domains->update('dom_…', ['inbound_domain' => 'reply.acme.com']);
// $domain['inbound_record']: ['type' => 'MX', 'name' => 'reply.acme.com', 'value' => 'inbound.postilon.com', 'priority' => 10, …]

Each message then reaches your webhooks as email.received, with its text and HTML (up to 256 KB), attachment list, SPF, DKIM and DMARC results and a spam flag. Read received email with $postilon->inbound->list(['q' => …]), get($id), attachment($id, $index) and raw($id); the last two return the bytes as a string. See Inbound email.

License

MIT, see LICENSE.