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.
Configuration
The key in the environment, never in the code:
export HERMAILY_API_KEY=hm_your_api_key
export HERMAILY_WEBHOOK_SECRET=hmwh_your_webhook_secretThe examples use requests (pip install requests); httpx works the same way.
Send a message
With requests (HTTP API)
import os
import requests
API = "https://api.hermaily.com"
HEADERS = {"Authorization": f"Bearer {os.environ['HERMAILY_API_KEY']}", "Accept-Language": "en"}
def send_email(**message) -> dict:
resp = requests.post(f"{API}/v1/send", headers=HEADERS, json=message, timeout=10)
if resp.status_code != 202:
# {"error": {"code", "message"}}, or plain text if the JSON itself is wrong
raise RuntimeError(f"Hermaily {resp.status_code}: {resp.text}")
return resp.json() # {"id", "to", "submitted_at", "status": "queued" | "held" | "suppressed"}
sent = send_email(
**{"from": "Acme <hello@acme.example>"}, # "from" is a Python keyword
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.",
tags=["shipping"],
metadata={"order_id": "48213"},
)
print(sent["id"], sent["status"])Batches and lookups with the same helper:
# Up to 500 messages per request; each one is admitted on its own.
messages = [
{"from": "Acme <hello@acme.example>", "to": c["email"], "subject": "Your invoice", "text": c["text"]}
for c in customers
]
resp = requests.post(f"{API}/v1/send/batch", headers=HEADERS, json=messages, timeout=30)
for item, result in zip(messages, resp.json()["data"]):
if "error" in result:
print(item["to"], result["error"]["code"], result["error"]["message"])
# Status and events of one message:
msg = requests.get(f"{API}/v1/messages/{sent['id']}", headers=HEADERS, timeout=10).json()
print(msg["status"], [e["type"] for e in msg["events"]])With smtplib (SMTP)
import os
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = "Acme <hello@acme.example>"
msg["To"] = "lucia@example.com"
msg["Subject"] = "Your order is on its way"
msg.set_content("Hi Lucía, order 48213 has shipped.")
msg.add_alternative("<p>Hi Lucía, order <b>48213</b> has shipped.</p>", subtype="html")
with smtplib.SMTP("smtp.hermaily.com", 587, timeout=10) as smtp:
smtp.starttls()
smtp.login("apikey", os.environ["HERMAILY_API_KEY"])
smtp.send_message(msg)
# Port 465: smtplib.SMTP_SSL("smtp.hermaily.com", 465) and no starttls().For a newsletter, add "stream": "broadcast" to the API body, or the header X-Hermaily-Stream: broadcast over SMTP (paid plans, one recipient per message).
Keep your SDK
If you already use sendgrid-python, postmark, the Mailgun SDK or resend, change the base URL and the key. Only sending is emulated; details in the migration guides (SendGrid, Mailgun, Postmark, Resend).
# sendgrid-python
sg = SendGridAPIClient(os.environ["HERMAILY_API_KEY"], host="https://api.hermaily.com")
# postmark (python)
with postmark.sync.ServerClient(os.environ["HERMAILY_API_KEY"], base_url="https://api.hermaily.com") as client:
...
# Mailgun Python SDK
client = Client(auth=("api", os.environ["HERMAILY_API_KEY"]), api_url="https://api.hermaily.com")
# resend
resend.api_key = os.environ["HERMAILY_API_KEY"]
resend.api_url = "https://api.hermaily.com"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.
A receiver that checks the signature:
import hashlib, hmac, os, time
from flask import Flask, abort, request
app = Flask(__name__)
def verify_hermaily(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
t = int(parts.get("t", "0") or 0)
if abs(time.time() - t) > tolerance:
return False
expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, parts.get("v1", ""))
@app.post("/webhooks/hermaily")
def hermaily_webhook():
if not verify_hermaily(request.get_data(), request.headers.get("X-Hermaily-Signature", ""),
os.environ["HERMAILY_WEBHOOK_SECRET"]):
abort(401)
event = request.get_json()
# event["type"]: "delivery", "bounce", "complaint"...; discard duplicates by event["id"]
return "", 204Event 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.
401 unauthorized
The key is missing, mistyped or revoked. Send it as Authorization: Bearer hm_... and check that the environment variable is really set where the code runs.
403 forbidden
The account cannot send yet (pending approval, paused, or new terms to accept), the key is restricted to the other stream, the From address is not on the key's domain, or the plan does not include broadcasts. GET https://api.hermaily.com/v1/domain tells you the key's domain, whether it is verified and whether the account can send.
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.
429 rate_limited or 402 quota_exceeded
429 is the per-minute limit or a new account's warm-up: wait and retry with a growing delay (there is no Retry-After). 402 is the Free plan's monthly quota, used up until next month or until you upgrade. 500 internal is safe to retry.
400 or 415 with a plain-text body
The body is not valid JSON, a required field is missing or has the wrong type, or the request lacks Content-Type: application/json. These answers are plain text, not the error object.
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.
Send your first message today
Create the account, verify your domain and paste the key. The free plan is enough to try it.