Ruby on Rails

Rails Action Mailer with Hermaily

Action Mailer delivers over SMTP out of the box. Point smtp_settings at Hermaily and your mailers, Devise emails and deliver_later jobs go through it unchanged.

  • SMTP smtp.hermaily.com:587
  • delivery_method = :smtp
  • Rails 6.1 and later

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.

Configuration

In the environment that sends (usually production):

Ruby · production.rb
# config/environments/production.rb
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  address: "smtp.hermaily.com",
  port: 587,
  user_name: "apikey",
  password: ENV.fetch("HERMAILY_API_KEY"),
  authentication: :plain,
  enable_starttls_auto: true,
  open_timeout: 5,
  read_timeout: 10
}
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_url_options = { host: "acme.example", protocol: "https" }

# Port 465 instead: port: 465 and tls: true (and drop enable_starttls_auto).

Or keep the key in Rails credentials instead of an environment variable:

YAML · credentials
# bin/rails credentials:edit
hermaily:
  api_key: hm_your_api_key
  webhook_secret: hmwh_your_webhook_secret

# and in smtp_settings:
#   password: Rails.application.credentials.dig(:hermaily, :api_key)

raise_delivery_errors = true makes SMTP errors raise instead of being swallowed: you want to see a 535 or a 550 the first day.

Send a message

The default sender, on your verified domain, and a mailer:

Ruby
# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
  default from: "Acme <hello@acme.example>"
  layout "mailer"
end

# app/mailers/order_mailer.rb
class OrderMailer < ApplicationMailer
  def shipped(order)
    @order = order
    headers["X-Entity-Ref-ID"] = order.id.to_s
    mail(to: order.email, subject: "Your order is on its way")
  end
end

# Anywhere: in the background with Active Job
OrderMailer.shipped(order).deliver_later

For a newsletter, mark the message for the broadcast stream (paid plans, one recipient per message; Hermaily adds the unsubscribe headers):

Ruby
class NewsletterMailer < ApplicationMailer
  def issue(subscriber, issue)
    headers["X-Hermaily-Stream"] = "broadcast"
    mail(to: subscriber.email, subject: issue.title)
  end
end

To try it from the console: bin/rails runner 'OrderMailer.shipped(Order.last).deliver_now'.

Events and webhooks

Every message gets an id: 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.

A receiver that checks the signature:

Ruby · controller
# config/routes.rb:  post "/webhooks/hermaily", to: "hermaily_webhooks#create"
# app/controllers/hermaily_webhooks_controller.rb
class HermailyWebhooksController < ActionController::API
  def create
    raw = request.raw_post
    parts = request.headers["X-Hermaily-Signature"].to_s.split(",").map { |p| p.split("=", 2) }.select { |a| a.size == 2 }.to_h
    t = parts["t"].to_i
    secret = Rails.application.credentials.dig(:hermaily, :webhook_secret)
    expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{t}.#{raw}")
    fresh = (Time.now.to_i - t).abs <= 300
    return head :unauthorized unless fresh && ActiveSupport::SecurityUtils.secure_compare(expected, parts["v1"].to_s)

    event = JSON.parse(raw)
    HermailyEventJob.perform_later(event)   # discard duplicates by event["id"]
    head :no_content
  end
end

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.

Hermaily signs every request with the secret shown when you created the webhook; keep it in credentials as above.

Troubleshooting

The errors you are most likely to see, with what they mean. The full list is in errors and limits.

Net::ReadTimeout or Net::OpenTimeout

On port 465 Rails needs tls: true (implicit TLS); with enable_starttls_auto on 465 it waits for a greeting that never comes. On 587, use enable_starttls_auto: true. If both ports time out, your host blocks outgoing SMTP.

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, send through the HTTP API on port 443 with Net::HTTP (endpoint and body in the documentation).

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