How to send email in PHP

Send email from PHP with the REST API and PHP's curl extension, or over SMTP with PHPMailer: attachments, safe retries, errors and delivery checks.

What you need

Send with the REST API

One POST to /v1/emails sends a message. Save this as send.php and run it with php send.php:

<?php
$body = [
    'from' => 'Acme <receipts@acme.example>',
    'to' => 'jo@acme.example',
    'subject' => 'Your receipt',
    'text' => 'Thanks for your order.',
];

$ch = curl_init('https://api.snd.email/v1/emails');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('SND_API_KEY'),
        'Content-Type: application/json',
        'Idempotency-Key: order-8812-receipt',
    ],
    CURLOPT_POSTFIELDS => json_encode($body),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT => 30,
]);
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

$result = json_decode($response, true);
if ($status !== 202) {
    throw new RuntimeException("$status {$result['code']}: {$result['detail']}");
}
echo $status, ' ', $result['id'], PHP_EOL;

The from address must be at a verified domain that the key may send from, as an address or as Name <address>. to is one address or a list; to, cc and bcc together hold at most 50 addresses. Give text, html or both.

The answer is 202 Accepted with the id of the request and one message per recipient, each with its own id. A message's status is queued, or suppressed when the address is on your suppression list and nothing is sent to it.

The same request can carry cc, bcc, reply_to, up to 5 tags, up to 10 metadata keys and custom headers. Every field is in the reference.

Send over SMTP

If your app already sends mail with PHPMailer, point it at the SMTP relay instead. SMTP is off until an Owner turns it on: in the dashboard, open SMTP and press Activate. Install PHPMailer with composer require phpmailer/phpmailer:

<?php
require 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;

$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.snd.email';
$mail->Port = 587;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->SMTPAuth = true;
$mail->Username = 'snd';
$mail->Password = getenv('SND_API_KEY');
$mail->CharSet = PHPMailer::CHARSET_UTF8;
$mail->setFrom('receipts@acme.example', 'Acme');
$mail->addAddress('jo@acme.example');
$mail->Subject = 'Your receipt';
$mail->Body = 'Thanks for your order.';
$mail->send();

The username can be any value; the password is the API key. Port 587 switches to TLS with STARTTLS before it logs in. Port 2525 works the same way where a host blocks 587; on port 465, which is TLS from the first byte, set SMTPSecure to PHPMailer::ENCRYPTION_SMTPS. Port 25 is not offered. With new PHPMailer(true), a refusal throws an exception that holds the server's reply.

Add an attachment

Over the REST API a file goes in the attachments list with its name, its bytes as base64 and its media type:

$body['attachments'] = [
    [
        'filename' => 'invoice.pdf',
        'content' => base64_encode(file_get_contents('invoice.pdf')),
        'content_type' => 'application/pdf',
    ],
];

The whole message is at most 10,000,000 bytes, headers and attachments included, with at most 100 files. Base64 makes a file about a third larger, so the largest file a message can carry is about 7.3 MB. A larger message is refused with 413 (payload_too_large), and a blocked file type, such as a program or an Office file with macros, with 422 (attachment_forbidden). With PHPMailer, call $mail->addAttachment('invoice.pdf').

Make retries safe

A timeout can leave you not knowing whether a message was accepted. The Idempotency-Key header makes a retry safe: send the same key with the same body again, and you get the first answer back, with the header Idempotent-Replayed: true, while nothing is sent twice. Take the key from your own data, such as the order the receipt is for.

Handle errors

Every error has a status of 400 or above and a body of type application/problem+json with type, title, status, code and detail. Act on code; each code has its own page:

StatusCodeWhat to do
400invalid_requestFix the field that errors[0].pointer names.
401unauthorizedCheck the key: it is missing, unknown, revoked or malformed.
403domain_out_of_scopeThe key may not send from the from domain: use a key for that domain.
422domain_not_verified, domain_declaration_requiredFinish the domain's setup in the dashboard.
429rate_limitedToo many requests at once: wait the seconds Retry-After names, at most a minute, then retry with the same Idempotency-Key.
429send_limit_reachedYour daily or monthly sending limit is used up. Do not retry: the daily limit starts again at 00:00 UTC, the monthly one on the first day of the month (UTC) on Free and with the plan's next monthly window on a paid plan; to raise it, contact support. With limit big_mail, large mail awaiting delivery fills its budget: retry after Retry-After.

A send that retries only what a retry can fix: rate_limited (by the problem's type), a server error and a network error. It waits as Retry-After asks but never more than 60 seconds, tries 3 times at most, and keeps the same Idempotency-Key. A daily or monthly send_limit_reached is final: its Retry-After can be weeks away; a big_mail one is retried.

function send(array $body, string $idempotencyKey): array
{
    for ($attempt = 1; ; $attempt++) {
        $headers = [];
        $ch = curl_init('https://api.snd.email/v1/emails');
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . getenv('SND_API_KEY'),
                'Content-Type: application/json',
                'Idempotency-Key: ' . $idempotencyKey,
            ],
            CURLOPT_POSTFIELDS => json_encode($body),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$headers) {
                $parts = explode(':', $line, 2);
                if (count($parts) === 2) {
                    $headers[strtolower(trim($parts[0]))] = trim($parts[1]);
                }
                return strlen($line);
            },
        ]);
        $response = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        curl_close($ch);
        $result = is_string($response) ? (json_decode($response, true) ?? []) : [];
        if ($status >= 200 && $status < 300) {
            return $result;
        }
        $retry = $response === false || $status >= 500
            || str_ends_with((string) ($result['type'] ?? ''), '/errors/rate_limited')
            || ($result['limit'] ?? '') === 'big_mail';
        if (!$retry || $attempt === 3) {
            // Final: a daily or monthly send_limit_reached starts again at 00:00 UTC or with the next monthly window.
            throw new RuntimeException($status . ' ' . ($result['code'] ?? 'error') . ': ' . ($result['detail'] ?? ''));
        }
        sleep(min(max((int) ($headers['retry-after'] ?? 1), 1), 60));
    }
}

All codes are in the error list.

Check delivery

GET /v1/emails/{id} with a message id returns its status and its newest 200 events. It needs a key with the emails:read scope:

$id = '1b9e4f7a-3c2d-4e5f-8a6b-7c9d0e1f2a3b';
$ch = curl_init('https://api.snd.email/v1/emails/' . $id);
curl_setopt_array($ch, [
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('SND_READ_KEY')],
    CURLOPT_RETURNTRANSFER => true,
]);
$message = json_decode(curl_exec($ch), true);
curl_close($ch);
echo $message['status'], PHP_EOL;

Rather than asking, let us tell you: a webhook sends each delivery, bounce, open or click to your endpoint as a signed request.

Troubleshooting

More on the API: the email API and the quick start.