Before you start
Three things from Hermaily before the first message:
- An account. Create one (there is a free plan). New accounts are reviewed before they can send; you can set everything up in the meantime.
- A verified domain. In Domains, the assistant gives you the DKIM, SPF and DMARC records and checks they are published. You can only send from addresses on that domain or its subdomains.
- An API key for that domain, created in API keys. It starts with
hm_and is shown only once: keep it in your secrets manager or in the environment, never in the repository. The same key is the SMTP password; the username isapikey.
Recommended: the official package
hermaily/hermaily-mailer sends through Hermaily's API over HTTPS (port 443) and verifies webhook signatures. It is built on the Symfony Mailer component, which works in any PHP project, framework or not. It is open source, under the MIT license, and the code is on GitHub. It needs PHP 8.2 or later; on older versions, use PHPMailer or curl below.
composer require hermaily/hermaily-mailerSend a message with tags and metadata (the key comes from the environment, see configuration):
<?php
use Hermaily\Mailer\Transport\HermailyApiTransport;
use Symfony\Component\Mailer\Header\MetadataHeader;
use Symfony\Component\Mailer\Header\TagHeader;
use Symfony\Component\Mime\Email;
require 'vendor/autoload.php';
$transport = new HermailyApiTransport(getenv('HERMAILY_API_KEY'));
$email = (new Email())
->from('Acme <hello@acme.example>')
->to('lucia@example.com')
->subject('Your order is on its way')
->html('<p>Hi Lucía, order <b>48213</b> has shipped.</p>')
->text('Hi Lucía, order 48213 has shipped.');
$email->getHeaders()->add(new TagHeader('shipping'));
$email->getHeaders()->add(new MetadataHeader('order_id', '48213'));
$sent = $transport->send($email); // throws a TransportException if Hermaily refuses it
echo $sent?->getMessageId(); // the Hermaily message idTags (up to 10) and metadata come back in every webhook; an X-Hermaily-Stream: broadcast header selects the broadcast stream. On failure, the exception carries Hermaily's message, code and HTTP status, for example Invalid API key (code unauthorized, HTTP 401). If you prefer a DSN, the package also has a transport factory for Symfony's Mailer:
use Hermaily\Mailer\Transport\HermailyTransportFactory;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport;
$transport = (new Transport([new HermailyTransportFactory()]))
->fromString('hermaily+api://' . getenv('HERMAILY_API_KEY') . '@default');
$mailer = new Mailer($transport);A webhook receiver that checks the signature (and its age, five minutes at most) and reads the event:
<?php
use Hermaily\Mailer\Webhook\EventType;
use Hermaily\Mailer\Webhook\Exception\InvalidSignatureException;
use Hermaily\Mailer\Webhook\WebhookParser;
use Hermaily\Mailer\Webhook\WebhookSignatureVerifier;
require 'vendor/autoload.php';
$parser = new WebhookParser(new WebhookSignatureVerifier(getenv('HERMAILY_WEBHOOK_SECRET')));
try {
$event = $parser->verifyAndParse(file_get_contents('php://input'), $_SERVER['HTTP_X_HERMAILY_SIGNATURE'] ?? '');
} catch (InvalidSignatureException) {
http_response_code(401);
exit;
}
if (EventType::Bounce === $event->eventType()) {
// $event->recipient, $event->message->metadata['order_id']...
}
// Discard duplicates by $event->id.
http_response_code(204);Configuration
The key in the server environment (for example SetEnv HERMAILY_API_KEY hm_... in Apache, fastcgi_param in nginx or the pool's env[...] in PHP-FPM), read with getenv(). Other PHP frameworks: Laravel, Symfony, WordPress.
Without the package
Without Composer, or on PHP older than 8.2, PHPMailer over SMTP or a plain curl call do the same job.
With PHPMailer (SMTP)
<?php
// composer require phpmailer/phpmailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.hermaily.com';
$mail->Port = 587;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 465: PHPMailer::ENCRYPTION_SMTPS
$mail->SMTPAuth = true;
$mail->Username = 'apikey';
$mail->Password = getenv('HERMAILY_API_KEY');
$mail->CharSet = PHPMailer::CHARSET_UTF8;
$mail->Timeout = 10;
$mail->setFrom('hello@acme.example', 'Acme');
$mail->addAddress('lucia@example.com', 'Lucía');
$mail->addCustomHeader('X-Entity-Ref-ID', '48213');
$mail->isHTML(true);
$mail->Subject = 'Your order is on its way';
$mail->Body = '<p>Hi Lucía, order <b>48213</b> has shipped.</p>';
$mail->AltBody = 'Hi Lucía, order 48213 has shipped.';
$mail->send();
} catch (Exception $e) {
error_log('Hermaily: ' . $mail->ErrorInfo); // contains the SMTP reply, e.g. 535 or 550
}For a newsletter, add $mail->addCustomHeader('X-Hermaily-Stream', 'broadcast'); and send one message per recipient (paid plans).
With curl (HTTP API)
Without dependencies, and with the message id in the response:
<?php
function hermaily_send(array $message): array
{
$ch = curl_init('https://api.hermaily.com/v1/send');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('HERMAILY_API_KEY'),
'Content-Type: application/json',
'Accept-Language: en',
],
CURLOPT_POSTFIELDS => json_encode($message, JSON_UNESCAPED_UNICODE),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($status !== 202) {
throw new RuntimeException("Hermaily $status: $body");
}
return json_decode($body, true); // ['id' => ..., 'status' => 'queued' | 'held' | 'suppressed']
}
$sent = hermaily_send([
'from' => 'Acme <hello@acme.example>',
'to' => 'lucia@example.com',
'subject' => 'Your order is on its way',
'html' => '<p>Hi Lucía, order <b>48213</b> has shipped.</p>',
'text' => 'Hi Lucía, order 48213 has shipped.',
'metadata' => ['order_id' => '48213'],
]);Keep your SDK
sendgrid-php, mailgun-php, postmark-php and resend-php keep working with a different base URL. Only sending is emulated; details in the migration guides (SendGrid, Mailgun, Postmark, Resend).
// sendgrid-php
$sendgrid = new \SendGrid(getenv('HERMAILY_API_KEY'), ['host' => 'https://api.hermaily.com']);
// mailgun-php
$mg = Mailgun::create(getenv('HERMAILY_API_KEY'), 'https://api.hermaily.com');
// postmark-php
PostmarkClientBase::$BASE_URL = 'https://api.hermaily.com';
$client = new PostmarkClient(getenv('HERMAILY_API_KEY'));
// resend-php: reads the host from the environment
putenv('RESEND_BASE_URL=api.hermaily.com');
$resend = Resend::client(getenv('HERMAILY_API_KEY'));Events and webhooks
Every message gets an id: over the API it comes in the 202 response and over SMTP it comes in the server's reply to the message (250 2.0.0 Ok: queued as <id>). Accepted means queued, not delivered. To know what happened next:
- Dashboard. Messages lists each message with its events: delivered, deferred, bounced, complaint, opened, clicked.
- API.
GET https://api.hermaily.com/v1/messages/{id}returns the current status and every event, oldest first (see looking up a message). - Webhooks. In Webhooks, add your URL (https and public) and the events you want. Hermaily makes one
POSTper event, signed withX-Hermaily-Signature: t=<unix>,v1=<hex>, wherev1isHMAC-SHA256(secret, t + "." + body)over the raw body. Answer any2xxwithin 10 seconds; otherwise it is retried for about a day and a half. Delivery is at least once, so discard duplicates by the eventid. The Test button sends a sample event to check your receiver.
With the package, the receiver is the one in the package section. Without it, a receiver that checks the signature:
<?php
// webhooks/hermaily.php
function hermaily_verify(string $rawBody, string $header, string $secret, int $tolerance = 300): bool
{
parse_str(str_replace(',', '&', $header), $parts);
$t = (int) ($parts['t'] ?? 0);
if (abs(time() - $t) > $tolerance) return false;
$expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
return hash_equals($expected, (string) ($parts['v1'] ?? ''));
}
$raw = file_get_contents('php://input');
if (!hermaily_verify($raw, $_SERVER['HTTP_X_HERMAILY_SIGNATURE'] ?? '', getenv('HERMAILY_WEBHOOK_SECRET'))) {
http_response_code(401);
exit;
}
$event = json_decode($raw, true);
// $event['type']: 'delivery', 'bounce', 'complaint'...; discard duplicates by $event['id']
http_response_code(204);Event types: send, delivery, delivery_delay, bounce, complaint, reject, rendering_failure, open, click and unsubscribe (opens and clicks only with tracking on). Permanent bounces, complaints and unsubscribes are suppressed automatically, so you do not need to keep your own list for that. Payload, fields and signature details are in the webhook documentation.
Troubleshooting
The errors you are most likely to see, with what they mean. The full list is in errors and limits.
SMTP connect() failed or Could not authenticate
PHPMailer hides the server's reply: set $mail->SMTPDebug = 2; while testing to see it. Could not authenticate is a 535 5.7.8 (wrong or revoked key); connect() failed is usually a closed port.
The connection hangs or times out
Your host blocks outgoing SMTP. Try port 465 with implicit TLS instead of 587. If both are closed, use the official package or the HTTP API with curl, which go over port 443.
550 5.7.1: the message is refused
The account cannot send right now (pending approval, paused, or new terms to accept), the key is restricted to the other stream, or the From address is not on the key's domain. Over the API this is 403 forbidden.
550 5.6.0: the message is rejected
Usually the From domain is not verified yet, there are more recipients than your plan allows (5 on Free, 50 on paid plans) or the message is too large. Over the API this is 422 validation, with the reason in the message.
422 validation
Sender domain not verified, empty subject, no recipient, more recipients than the plan allows, an invalid address or base64, or a message that is too large. The message says which; it follows Accept-Language (Spanish by default, so send Accept-Language: en). Code against code, not the text.
Send your first message today
Create the account, verify your domain and paste the key. The free plan is enough to try it.