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 Symfony's secrets vault 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 is a Symfony Mailer transport for Hermaily: hermaily+api:// sends through Hermaily's API over HTTPS (port 443, so it also works where outgoing SMTP is blocked), with TagHeader and MetadataHeader as the message's tags and metadata, and the bundle also gives you 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 Symfony 6.4, 7.x or 8.x.
composer require hermaily/hermaily-mailerThere is no Flex recipe yet, so register the bundle yourself:
return [
// ...
Hermaily\Mailer\Symfony\HermailyMailerBundle::class => ['all' => true],
];and point the DSN at it:
HERMAILY_API_KEY=hm_your_api_key
MAILER_DSN=hermaily+api://${HERMAILY_API_KEY}@default| DSN | Transport |
|---|---|
hermaily+api://KEY@default (or hermaily://KEY@default) | API, POST https://api.hermaily.com/v1/send with Authorization: Bearer |
hermaily+smtp://KEY@default | SMTP, smtp.hermaily.com port 587 (STARTTLS), user apikey |
hermaily+smtps://KEY@default | SMTP, smtp.hermaily.com port 465 (implicit TLS) |
With the API transport, ?lang=es returns the error messages in Spanish (English by default). The mailer.yaml below (default sender, recipients in development) and Messenger work the same with this DSN. Tags and metadata use Symfony's standard headers:
use Symfony\Component\Mailer\Header\MetadataHeader;
use Symfony\Component\Mailer\Header\TagHeader;
$email->getHeaders()
->add(new TagHeader('order-shipped'))
->add(new MetadataHeader('order_id', (string) $order->getId()));Over the API, each TagHeader becomes a tag (up to 10) and each MetadataHeader an entry of metadata, which comes back in every webhook; X-Hermaily-Stream: broadcast selects the broadcast stream. Over hermaily+smtp:// tags and the stream still work, but there is no metadata nor click tracking: use the API for those. On failure, the exception carries Hermaily's message, code and HTTP status, for example Invalid API key (code unauthorized, HTTP 401).
For webhooks, give the bundle the signing secret and inject WebhookParser, which checks the signature (and its age, five minutes at most) before reading the event:
hermaily_mailer:
webhook:
secret: '%env(HERMAILY_WEBHOOK_SECRET)%'namespace App\Controller;
use Hermaily\Mailer\Webhook\Exception\InvalidSignatureException;
use Hermaily\Mailer\Webhook\WebhookParser;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Routing\Attribute\Route;
#[AsController]
final class HermailyWebhookController
{
#[Route('/webhooks/hermaily', methods: ['POST'])]
public function __invoke(Request $request, WebhookParser $parser): Response
{
try {
$event = $parser->verifyAndParse($request->getContent(), (string) $request->headers->get('X-Hermaily-Signature'));
} catch (InvalidSignatureException) {
return new Response(status: Response::HTTP_UNAUTHORIZED);
}
// $event->id (for duplicates), $event->type, $event->recipient, $event->message->metadata['order_id']...
return new Response(status: Response::HTTP_NO_CONTENT);
}
}Without the package: SMTP
Symfony's own SMTP transport needs nothing else. Symfony Mailer is already in the webapp skeleton; otherwise, composer require symfony/mailer. Put the DSN in the environment, with your key as the password:
HERMAILY_API_KEY=hm_your_api_key
MAILER_DSN=smtp://apikey:${HERMAILY_API_KEY}@smtp.hermaily.com:587Port 587 negotiates STARTTLS by itself (auto_tls is on by default). Keys are base64url (letters, digits, - and _), so they need no URL encoding in the DSN; any other credential with @, :, / or # must go through urlencode(). If your host blocks 587, use implicit TLS on 465:
# Port 465 (implicit TLS) instead of 587:
MAILER_DSN=smtps://apikey:${HERMAILY_API_KEY}@smtp.hermaily.com:465
# Symfony 7.3 and later: fail instead of sending in clear if STARTTLS were missing
MAILER_DSN=smtp://apikey:${HERMAILY_API_KEY}@smtp.hermaily.com:587?require_tls=trueIn production, keep the key out of files: APP_RUNTIME_ENV=prod php bin/console secrets:set MAILER_DSN stores the whole DSN in the encrypted vault, and %env(MAILER_DSN)% reads it the same way. Then, in config/packages/mailer.yaml, a default sender for every message:
framework:
mailer:
dsn: '%env(MAILER_DSN)%'
headers:
From: 'Acme <hello@acme.example>'
when@dev:
framework:
mailer:
envelope:
# In development, everything goes to you whatever the To says.
recipients: ['you@acme.example']The From address must be on your verified domain. Leave envelope.sender unset: bounces come back to Hermaily, which turns them into events and suppresses the address; you do not need a return path of your own.
Send a message
Inject MailerInterface and send an Email. With a TemplatedEmail (needs symfony/twig-bundle), the body comes from Twig:
namespace App\Service;
use App\Entity\Order;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
final class OrderMailer
{
public function __construct(private readonly MailerInterface $mailer)
{
}
public function shipped(Order $order): void
{
$email = (new TemplatedEmail())
->to(new Address($order->getCustomerEmail(), $order->getCustomerName()))
->subject('Your order is on its way')
->htmlTemplate('emails/order_shipped.html.twig')
->textTemplate('emails/order_shipped.txt.twig')
// Plain values, not the entity: with Messenger the context is serialized.
->context(['number' => $order->getNumber(), 'name' => $order->getCustomerName()]);
// From comes from mailer.yaml; set ->from() here to override it.
$this->mailer->send($email);
}
}A quick test from the console, with no code: php bin/console mailer:test you@example.com --from=hello@acme.example. On failure, send() throws a TransportExceptionInterface whose message carries the SMTP reply (see troubleshooting).
Newsletters and announcements go through the broadcast stream (paid plans, one recipient per message, unsubscribe link added by Hermaily). Mark them with a header:
// A newsletter: send it through the broadcast stream.
$email->getHeaders()->addTextHeader('X-Hermaily-Stream', 'broadcast');Without the header, every message is transactional. More about streams in the documentation.
Asynchronous sending with Messenger
In production, do not make the request wait for SMTP. With Messenger installed, $mailer->send() dispatches a SendEmailMessage; route it to an asynchronous transport and a worker sends it:
framework:
messenger:
failure_transport: failed
transports:
async:
dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
retry_strategy:
max_retries: 5
delay: 60000 # 1 minute, then 2, 4, 8...
multiplier: 2
failed: 'doctrine://default?queue_name=failed'
routing:
'Symfony\Component\Mailer\Messenger\SendEmailMessage': asyncRun the worker with php bin/console messenger:consume async under a process manager (systemd or Supervisor). Temporary replies such as 451 4.7.1 become retries with that delay; what still fails ends in the failed transport, which you can review with messenger:failed:show and retry with messenger:failed:retry. Twig renders the templates in the worker, right before sending, so the context of a TemplatedEmail must be serializable: pass ids and plain values, not Doctrine entities. mailer:test skips the bus and sends straight away, which helps to tell a Hermaily problem from a stopped worker.
Without the package: the Mailgun bridge
The API transports of Symfony's provider bridges let you replace default in the DSN with another host, and Hermaily accepts Mailgun's request on the same path (POST /v3/{domain}/messages, multipart with its fields and attachments). That way TagHeader becomes the message tag and each MetadataHeader comes back in every webhook, which SMTP does not carry. It also goes over port 443 when SMTP is blocked.
# composer require symfony/mailgun-mailer symfony/http-client
MAILER_DSN=mailgun+api://${HERMAILY_API_KEY}:acme.example@api.hermaily.comuse Symfony\Component\Mailer\Header\MetadataHeader;
use Symfony\Component\Mailer\Header\TagHeader;
$email->getHeaders()
->add(new TagHeader('order-shipped'))
->add(new MetadataHeader('order_id', (string) $order->getId()));Use the mailgun+api scheme: mailgun:// and mailgun+https:// post the raw MIME message to another path, which Hermaily does not emulate. The domain after the colon is required by the bridge but ignored by Hermaily (the sender is checked against your verified domains). Each TagHeader becomes a tag of the message (up to 10). The X-Hermaily-Stream header above still works, because the bridge forwards custom headers as h: fields. The Postmark and SendGrid bridges also work with the same change (postmark+api://${HERMAILY_API_KEY}@api.hermaily.com, sendgrid+api://${HERMAILY_API_KEY}@api.hermaily.com); the details of each compatible endpoint are in migrate from Mailgun.
The native API with HttpClient
To call Hermaily's own API (the message id in the response, batches, message lookup), declare a scoped client with the key as Authorization: Bearer:
framework:
http_client:
scoped_clients:
hermaily.client:
base_uri: 'https://api.hermaily.com'
auth_bearer: '%env(HERMAILY_API_KEY)%'Symfony autowires it by argument name ($hermailyClient):
use Symfony\Contracts\HttpClient\HttpClientInterface;
public function __construct(private readonly HttpClientInterface $hermailyClient)
{
}
public function shipped(Order $order, string $html): string
{
$response = $this->hermailyClient->request('POST', '/v1/send', [
'json' => [
'from' => 'Acme <hello@acme.example>',
'to' => [$order->getCustomerEmail()],
'subject' => 'Your order is on its way',
'html' => $html,
'tags' => ['shipping'],
'metadata' => ['order_id' => (string) $order->getId()],
],
]);
// 202 Accepted; on 4xx or 5xx, toArray() throws and the body is {"error": {"code", "message"}}.
return $response->toArray()['id'];
}The full list of fields (cc, reply_to, headers, attachments, stream, tracking) is in the API documentation.
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>), which Symfony stores as the SentMessage id. MailerInterface::send() returns nothing, so read it in a listener, which also runs inside the Messenger worker:
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Mailer\Event\SentMessageEvent;
#[AsEventListener]
final class StoreHermailyId
{
public function __invoke(SentMessageEvent $event): void
{
$id = $event->getMessage()->getMessageId(); // the Hermaily id
// Store it next to your order to match the webhooks later.
}
}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, use the controller in the package section. Without it, a controller that checks the signature and hands the work to Messenger:
namespace App\Controller;
use App\Message\HermailyEvent;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;
#[AsController]
final class HermailyWebhookController
{
public function __construct(
#[Autowire(env: 'HERMAILY_WEBHOOK_SECRET')] private readonly string $secret,
private readonly MessageBusInterface $bus,
) {
}
#[Route('/webhooks/hermaily', methods: ['POST'])]
public function __invoke(Request $request): Response
{
$raw = $request->getContent();
$header = (string) $request->headers->get('X-Hermaily-Signature', '');
parse_str(str_replace(',', '&', $header), $parts);
$t = (int) ($parts['t'] ?? 0);
$expected = hash_hmac('sha256', $t . '.' . $raw, $this->secret);
if (abs(time() - $t) > 300 || !hash_equals($expected, (string) ($parts['v1'] ?? ''))) {
return new Response(status: Response::HTTP_UNAUTHORIZED);
}
// App\Message\HermailyEvent is a small readonly class with the decoded array;
// its #[AsMessageHandler] discards duplicates by $event['id'].
$this->bus->dispatch(new HermailyEvent(json_decode($raw, true, flags: \JSON_THROW_ON_ERROR)));
return new Response(status: Response::HTTP_NO_CONTENT);
}
}If the firewall covers that path, leave it out of authentication (it is a public endpoint whose security is the signature). 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.
With the Webhook component
If you prefer Symfony's Webhook and RemoteEvent components, create the webhook in Hermaily in Mailgun format: its signature and its event-data are the ones Symfony's Mailgun parser checks, so there is no parser to write. The parser rejects anything with a wrong signature or a timestamp more than five minutes old.
# composer require symfony/webhook symfony/mailgun-mailer
framework:
webhook:
routing:
hermaily: # the URL is /webhook/hermaily
service: mailer.webhook.request_parser.mailgun
secret: '%env(HERMAILY_WEBHOOK_SECRET)%'namespace App\RemoteEvent;
use Symfony\Component\RemoteEvent\Attribute\AsRemoteEventConsumer;
use Symfony\Component\RemoteEvent\Consumer\ConsumerInterface;
use Symfony\Component\RemoteEvent\Event\Mailer\MailerDeliveryEvent;
use Symfony\Component\RemoteEvent\Event\Mailer\MailerEngagementEvent;
use Symfony\Component\RemoteEvent\RemoteEvent;
#[AsRemoteEventConsumer('hermaily')]
final class HermailyConsumer implements ConsumerInterface
{
public function consume(RemoteEvent $event): void
{
// $event->getId() is the event id (for duplicates); the Hermaily message id is in the payload.
$messageId = $event->getPayload()['message']['headers']['message-id'] ?? null;
if ($event instanceof MailerDeliveryEvent) {
// getName(): received, delivered, deferred, bounce or dropped; getReason() on failures.
} elseif ($event instanceof MailerEngagementEvent) {
// getName(): open, click, spam or unsubscribe.
}
// getRecipientEmail(), getMetadata() and getTags() on both.
}
}To consume the events in the worker instead of during the request, route Symfony\Component\RemoteEvent\Messenger\ConsumeRemoteEventMessage to async in messenger.yaml. The Mailgun format names and the full mapping are in migrate from Mailgun.
Troubleshooting
The errors you are most likely to see, with what they mean. Over SMTP, Symfony's exception reads Expected response code "250" but got code "550", with message "...": the reply inside is the one below. The full list is in errors and limits.
A new MAILER_DSN has no effect
If you deploy with composer dump-env prod, the values live in .env.local.php: run it again. Then clear the cache (php bin/console cache:clear) and restart the Messenger workers with php bin/console messenger:stop-workers, because a running worker keeps the transport it started with.
535 5.7.8: authentication failed
Symfony reports it as Failed to authenticate on SMTP server, with the 535 reply inside. The password must be the whole API key (hm_...), not revoked, and the variable it comes from must really be set (an empty ${HERMAILY_API_KEY} leaves the DSN without a password). The username can be anything; use apikey. After many failed attempts from the same IP, logins are refused for a few minutes.
Connection could not be established, or it times out
Your host blocks outgoing SMTP. Try smtps:// on port 465 instead of 587. If both are closed, use the official package (hermaily+api://), the Mailgun bridge or HttpClient, which go 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: with Messenger the message is retried according to the transport's retry_strategy (over the API, 429 rate_limited). 552 5.3.4 means the monthly quota of the Free plan is used up (402 quota_exceeded).
The Mailgun bridge fails with code 404
The DSN uses mailgun:// or mailgun+https://, which post the raw MIME message to a path Hermaily does not emulate. Use mailgun+api://, which posts the form that Hermaily accepts.
Send your first message today
Create the account, verify your domain and put the key in MAILER_DSN. The free plan is enough to try it.