Sending transactional email from plain PHP (with retries, attachments and verified webhooks)
Most PHP projects I work on still send email with mail() or a hand-configured SMTP account, and sooner or later the same problems show up: messages landing in spam because DKIM was never set up, no idea whether an email
Most PHP projects I work on still send email with mail() or a hand-configured SMTP account, and sooner or later the same problems show up: messages landing in spam because DKIM was never set up, no idea whether an email was delivered, and bounced addresses that keep getting mailed until the provider complains.
This post shows a small, dependency-free setup for sending transactional email from PHP over an HTTP API. I'll use Zend24, the API I built on top of Amazon SES, but the patterns (keys out of the code, timeouts and retries, signed webhooks) apply to any provider.
1. Keep the API key out of your code
The key goes in an environment variable or in a config file outside the document root, never in the repository or in anything the browser can see.
// config/bootstrap.php (outside public/)
$apiKey = getenv('ZEND24_API_KEY');
if (!$apiKey) {
throw new RuntimeException('ZEND24_API_KEY is not set');
}
Add .env to your .gitignore and commit a .env.example with an empty value:
ZEND24_API_KEY=
2. A minimal send function
One POST with a JSON body. Set a connection timeout and a total timeout so a slow network never blocks your request handler.
function sendEmail(array $payload, string $apiKey): array
{
$ch = curl_init('https://zend24.com/api/v1/emails');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode($payload, JSON_THROW_ON_ERROR),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($body === false) {
return ['ok' => false, 'status' => 0, 'error' => $error];
}
$data = json_decode($body, true) ?? [];
return ['ok' => $status === 200, 'status' => $status, 'data' => $data];
}
$result = sendEmail([
'from' => 'Shop <[email protected]>',
'to' => '[email protected]',
'subject' => 'Your order #1042',
'html' => '<h1>Thanks for your order</h1>',
'text' => 'Thanks for your order',
], $apiKey);
A successful call returns the message id, which you can store next to the order to check its status later with GET /emails/{id}.
3. Retry only what is worth retrying
Not every error deserves a retry. A 422 means the payload is wrong and will fail again; a 401 means the key is wrong. Network errors, 429 (rate limit) and 5xx are temporary.
function sendWithRetry(array $payload, string $apiKey, int $maxAttempts = 3): array
{
for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
$result = sendEmail($payload, $apiKey);
$retryable = $result['status'] === 0
|| $result['status'] === 429
|| $result['status'] >= 500;
if ($result['ok'] || !$retryable) {
return $result;
}
// Exponential backoff with a little jitter: ~1s, ~2s, ~4s
usleep((int) ((2 ** ($attempt - 1)) * 1_000_000 + random_int(0, 250_000)));
}
return $result;
}
If you send from a web request, keep $maxAttempts low or push the email to a queue (a table plus a cron job is enough) so the user never waits for retries.
4. Attachments
Attachments travel as base64 inside the same JSON. Read the file from a path you control, never from a path built with user input.
$pdf = file_get_contents(__DIR__ . '/../storage/invoices/1042.pdf');
$payload['attachments'] = [[
'filename' => 'invoice-1042.pdf',
'content_type' => 'application/pdf',
'content' => base64_encode($pdf),
]];
5. Verify webhooks before trusting them
Delivery, bounce and complaint events arrive as POST requests to an endpoint on your server. Anyone can POST to that URL, so verify the signature first. Zend24 sends X-Zend24-Timestamp and X-Zend24-Signature: v1=HMAC_SHA256(timestamp.body, secret).
// public/webhooks/zend24.php
$secret = getenv('ZEND24_WEBHOOK_SECRET');
$body = file_get_contents('php://input');
$timestamp = $_SERVER['HTTP_X_ZEND24_TIMESTAMP'] ?? '';
$signature = $_SERVER['HTTP_X_ZEND24_SIGNATURE'] ?? '';
// Reject old timestamps to block replayed requests
if (!ctype_digit($timestamp) || abs(time() - (int) $timestamp) > 300) {
http_response_code(400);
exit;
}
$expected = 'v1=' . hash_hmac('sha256', $timestamp . '.' . $body, $secret);
// hash_equals avoids timing attacks; never compare signatures with ==
if (!hash_equals($expected, $signature)) {
http_response_code(401);
exit;
}
$event = json_decode($body, true);
// Event names: email.sent, email.delivered, email.bounced,
// email.complained, email.opened, email.clicked
// (check the payload format in your provider's docs)
$type = $event['type'] ?? '';
switch ($type) {
case 'email.bounced':
case 'email.complained':
// Mark the address as undeliverable in your own users table
break;
case 'email.delivered':
// Update the order's email status
break;
}
http_response_code(200);
Two details that are easy to miss: read the raw body with php://input (not $_POST), because the signature is computed over the exact bytes; and answer quickly with a 200, doing any slow work afterwards, so the provider doesn't time out and retry.
6. Don't keep mailing addresses that bounce
Sending to addresses that hard-bounce or that marked you as spam hurts deliverability for everyone on your domain. Zend24 adds those addresses to a suppression list automatically, and you can check or clear it with GET /suppressions and DELETE /suppressions/{email}. Whatever provider you use, mirror that status in your own database so your app stops trying.
Wrapping up
The whole integration is one function, one retry wrapper and one webhook endpoint, with no SDK or Composer package. The parts that matter most are boring: keep the key out of the code, set timeouts, retry only temporary errors, and verify every webhook.
If you want to try it, Zend24 has a free plan with 3,000 emails a month: zend24.com. I'd like to hear how you handle bounces and retries in your own PHP projects.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.