Laravel

Laravel email with Hermaily

With the official package, Hermaily is one more mailer in Laravel: your Mailables, notifications and queues stay as they are, and tags and metadata reach Hermaily. Without the package, Laravel's SMTP mailer works too, with a change in .env. This guide covers the package, the SMTP mailer, the Mailgun mailer pointed at Hermaily, webhooks and common errors.

  • composer require hermaily/hermaily-mailer
  • MAIL_MAILER=hermaily
  • Without the package: SMTP smtp.hermaily.com:587

Before you start

Three things from Hermaily before the first message:

  1. 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.
  2. 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.
  3. 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 is apikey.

Recommended: the official package

hermaily/hermaily-mailer adds a hermaily mail transport that sends through Hermaily's API over HTTPS (port 443, so it also works where outgoing SMTP is blocked), plus a verifier for the webhook signature. It is open source, under the MIT license, and the code is on GitHub. It needs PHP 8.2 or later and Laravel 11 or 12; on Laravel 9 or 10, use SMTP.

Terminal
composer require hermaily/hermaily-mailer

The service provider is discovered on its own. Add the mailer to config/mail.php:

config/mail.php
'mailers' => [
    // ...
    'hermaily' => [
        'transport' => 'hermaily',
        'key' => env('HERMAILY_API_KEY'),
        // 'lang' => 'en',   // language of the API error messages: en or es
    ],
],

and select it in .env:

.env
MAIL_MAILER=hermaily
HERMAILY_API_KEY=hm_your_api_key
MAIL_FROM_ADDRESS="hello@acme.example"
MAIL_FROM_NAME="Acme"

Mailables and notifications go out as usual (see send a message). Laravel's tag() and metadata() become the message's tags (up to 10) and metadata, which come back in every webhook:

PHP
Mail::to($order->customer_email)->queue(
    (new OrderShipped($order))
        ->tag('shipping')
        ->metadata('order_id', (string) $order->id)
);

For webhooks, put the signing secret in config/services.php; the package then gives you a WebhookParser that checks the signature (and its age, five minutes at most) before reading the event:

config/services.php
'hermaily' => [
    'webhook_secret' => env('HERMAILY_WEBHOOK_SECRET'),
],
Laravel · routes/api.php
use Hermaily\Mailer\Webhook\Exception\InvalidSignatureException;
use Hermaily\Mailer\Webhook\WebhookParser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/webhooks/hermaily', function (Request $request, WebhookParser $parser) {
    try {
        $event = $parser->verifyAndParse($request->getContent(), (string) $request->header('X-Hermaily-Signature'));
    } catch (InvalidSignatureException) {
        abort(401);
    }
    // $event->id (for duplicates), $event->type, $event->recipient, $event->message->metadata['order_id']...
    return response()->noContent();
});

When a send fails, the package throws an exception with Hermaily's message, its code and the HTTP status (for example Invalid API key (code unauthorized, HTTP 401)). Everything it maps, field by field, is in its README.

Without the package: SMTP

Laravel's SMTP mailer needs nothing to install and works on any version. In .env, the SMTP mailer with your key as the password:

.env
MAIL_MAILER=smtp
MAIL_HOST=smtp.hermaily.com
MAIL_PORT=587
MAIL_USERNAME=apikey
MAIL_PASSWORD=hm_your_api_key
MAIL_FROM_ADDRESS="hello@acme.example"
MAIL_FROM_NAME="Acme"

Port 587 negotiates STARTTLS by itself. If your host blocks it, use 465:

.env
# Port 465 (implicit TLS) instead of 587:
MAIL_PORT=465
MAIL_SCHEME=smtps        # Laravel 11 and later
# MAIL_ENCRYPTION=ssl    # Laravel 10 and earlier

MAIL_FROM_ADDRESS must be on your verified domain. If the configuration is cached in production, run php artisan config:clear (or config:cache again) after changing .env.

Send a message

Any Mailable or notification goes out through Hermaily. A quick test from Tinker:

Tinker
php artisan tinker
> Mail::raw('Test from Hermaily', fn ($m) => $m->to('you@example.com')->subject('Test'));

And in your code, preferably through the queue:

PHP
use App\Mail\OrderShipped;
use Illuminate\Support\Facades\Mail;

Mail::to($order->customer_email)->send(new OrderShipped($order));

// Or through the queue, so the request does not wait for SMTP:
Mail::to($order->customer_email)->queue(new OrderShipped($order));

Newsletters and announcements go through the broadcast stream (paid plans, one recipient per message, unsubscribe link added by Hermaily). Mark them with a header:

PHP · Mailable
use Illuminate\Mail\Mailables\Headers;

// In a newsletter Mailable: send it through the broadcast stream.
public function headers(): Headers
{
    return new Headers(text: ['X-Hermaily-Stream' => 'broadcast']);
}

Without the header, every message is transactional. More about streams in the documentation.

Without the package: the Mailgun mailer

If you cannot add the package, Laravel's Mailgun mailer lets you change its endpoint, and Hermaily accepts Mailgun's request on the same path. That way each of Laravel's tag() calls becomes a tag of the message (up to 10) and metadata() comes back in every webhook, which SMTP does not carry.

.env
# composer require symfony/mailgun-mailer symfony/http-client
MAIL_MAILER=mailgun
MAILGUN_DOMAIN=acme.example
MAILGUN_SECRET=hm_your_api_key
MAILGUN_ENDPOINT=api.hermaily.com
PHP
// config/mail.php, in the 'mailers' array (Laravel 11 and later no longer ship it)
'mailgun' => [
    'transport' => 'mailgun',
],

// config/services.php (also missing since Laravel 11: add it)
'mailgun' => [
    'domain' => env('MAILGUN_DOMAIN'),
    'secret' => env('MAILGUN_SECRET'),
    'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
    'scheme' => 'https',
],

MAILGUN_DOMAIN is ignored by Hermaily (the sender is checked against your verified domains), but Laravel needs it. The details of the compatible endpoint are in migrate from Mailgun.

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 POST per event, signed with X-Hermaily-Signature: t=<unix>,v1=<hex>, where v1 is HMAC-SHA256(secret, t + "." + body) over the raw body. Answer any 2xx within 10 seconds; otherwise it is retried for about a day and a half. Delivery is at least once, so discard duplicates by the event id. 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:

Laravel · routes/api.php
// routes/api.php (no CSRF there). HERMAILY_WEBHOOK_SECRET in .env,
// read through config/services.php: 'hermaily' => ['webhook_secret' => env('HERMAILY_WEBHOOK_SECRET')]
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/webhooks/hermaily', function (Request $request) {
    $raw = $request->getContent();
    $header = (string) $request->header('X-Hermaily-Signature', '');
    parse_str(str_replace(',', '&', $header), $parts);
    $t = (int) ($parts['t'] ?? 0);
    $expected = hash_hmac('sha256', $t . '.' . $raw, config('services.hermaily.webhook_secret'));
    if (abs(time() - $t) > 300 || ! hash_equals($expected, (string) ($parts['v1'] ?? ''))) {
        abort(401);
    }
    $event = json_decode($raw, true);
    // Do the work in a job and answer right away; discard duplicates by $event['id'].
    \App\Jobs\HandleHermailyEvent::dispatch($event);
    return response()->noContent();
});

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.

Changes in .env have no effect

The configuration is cached: run php artisan config:clear, or php artisan config:cache to rebuild it, and restart the queue workers (php artisan queue:restart), which keep the old settings in memory.

535 5.7.8: authentication failed

The password must be the whole API key (hm_...), copied without spaces and not revoked. The username can be anything; use apikey. After many failed attempts from the same IP, logins are refused for a few minutes.

The connection hangs or times out

Your host blocks outgoing SMTP. Try port 465 with implicit TLS instead of 587. If both are closed, switch to the official package (or the Mailgun mailer), which goes over HTTPS (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.

451 4.7.1: try again later

The plan's per-minute limit or a new account's daily warm-up limit. It is temporary: retry later (over the API, 429 rate_limited). 552 5.3.4 means the monthly quota of the Free plan is used up (402 quota_exceeded).

Send your first message today

Create the account, verify your domain and paste the key. The free plan is enough to try it.

Create a free account