When a Rails app of mine sends an email in development, letter_opener opens it in a browser tab. I have also used MailCatcher, a local SMTP server with a web page listing what it caught. Either way it is a delivery setting for the development environment.

The companion app of this series, a small CTF challenge tracker in Hanami 3, has exactly one email to send. Accounts are created from a rake task by whoever runs the server, and the welcome email gives the new user the sign-in link.

The mailer is the familiar part

hanami generate mailer welcome writes a class, an HTML template, a text template and a spec. The class declares its headers and exposes values to the templates, the way a view does:

class Welcome < CtfTracker::Mailer
  include Deps["i18n", "settings"]

  from "ctf-tracker@localhost"
  to { |user:| user.email }
  subject { |user:| i18n.t("mailers.welcome.subject", name: user.name) }

  expose :user
  expose :sign_in_url do
    "#{settings.base_url}/sign_in"
  end
end

The templates render through Hanami View, so t(".greeting") resolves to mailers.welcome.greeting, and the escaping from the post on escaping applies to email too: a link inside a translated sentence only survives in a key marked HTML-safe by its name, ending in _html or with html as its last segment, the same convention as Rails. Two differences are worth knowing before writing a spec. The message is Hanami’s own Hanami::Mailer::Message, with text_body and html_body, not a Mail::Message with parts. And there is no deliver_later: deliver sends synchronously and returns a result. For a rake task that is fine.

Where the email went

I created an account in development, and nothing happened. That is what the delivery guide promises: “In development, it’s the test delivery method unless you’ve configured SMTP.” The test delivery method keeps messages in memory, so the email was delivered to an array inside a rake process that exited right after. With Hanami’s own provider, a delivery in development reports a success:

env: development, SMTP_ADDRESS=nil
delivery method: Hanami::Mailer::Delivery::Test
success? true, error: nil
kept in memory: 1

Production without SMTP does the same thing with a warning in the log:

No SMTP configuration found for ctf_tracker in production; falling back to the test delivery method — mail will NOT be sent. Set SMTP_ADDRESS (and related SMTP_* variables), or register a custom :mailers provider.

The last words of that warning are the way out. Mail delivery is a provider, and an app can register its own.

Taking over the provider

The guide is clear about the cost: “When you register your own provider, it replaces Hanami’s own,” so the app also has to keep the test delivery method under test. Replacing the provider replaces its whole environment policy.

My first version answered the development question with the simplest object the guide allows, since “a delivery method is any object that responds to #call(message) and returns a result”. A small class wrote each message to a file, and the provider picked it by environment:

delivery_method =
  case Hanami.env
  when :test
    Hanami::Mailer::Delivery::Test.new
  when :development
    CtfTracker::Mailbox.new(target.root.join("tmp/mail"))
  else
    # ...

It worked, and the file was readable. Coming back to it, I asked myself why I had not reached for letter_opener, my usual tool in Rails. It is a delivery method for the mail gem: its setup outside Rails goes through Mail.defaults, and it expects a Mail::Message. Hanami hands its delivery methods a Hanami::Mailer::Message. The conversion exists, in Hanami::Mailer::Delivery::SMTP, but it is a private method of that class, so plugging letter_opener in would mean copying it or calling it from outside.

Looking at that conversion is what condemned the file. The SMTP delivery turns the Hanami message into a multipart MIME message, and my file skipped that step entirely: what I read in development was not what a user would receive. Mailpit, which the app uses, is an SMTP server like MailCatcher. Pointing development at one sends the email through the very code production runs:

Hanami.app.register_provider(:mailers, namespace: true) do
  start do
    require "hanami/mailer"

    delivery_method =
      if Hanami.env?(:test)
        Hanami::Mailer::Delivery::Test.new
      else
        settings = target["settings"]
        raise ArgumentError, "SMTP_ADDRESS is not set: there is nowhere to hand the mail" if settings.smtp_address.nil?

        Hanami::Mailer::Delivery::SMTP.new(
          address: settings.smtp_address,
          port: settings.smtp_port,
          user_name: settings.smtp_username,
          password: settings.smtp_password,
          authentication: settings.smtp_authentication
        )
      end

    register "delivery_method", delivery_method
  end
end

Development gets its address from a .env.development that no other environment reads:

SMTP_ADDRESS=localhost
SMTP_PORT=1025

Mailpit's web interface showing the welcome email from the companion app:
  sent from ctf-tracker@localhost to grace@example.org, subject Your CTF
  tracker account, Grace, and the HTML body with the sign-in link
  rendered.

The welcome email in Mailpit, after the same SMTP delivery production uses. The HTML, Text, Headers and Raw tabs show the multipart message the file in tmp/mail never built.

To be fair to the framework, Mailpit alone did not need any of this. With Hanami’s own provider, the same two variables are enough:

Hanami::Mailer::Delivery::SMTP
{address: "localhost", port: 1025}

What the replacement buys is the production policy. The app reads typed settings, not raw environment variables, and it refuses to go on without an address where Hanami’s provider would drop mail with a warning. Owning the provider also means owning its defaults. The settings first gave smtp_authentication a default of "plain", which the built-in provider never sets, and net-smtp refuses an authentication type that comes without a user name, which is exactly the case of a local Mailpit:

ArgumentError: SMTP-AUTH requested but missing user name

The setting has no default now.

A refusal that waits to be asked

“Refuses to go on” deserves a closer look. As the post on i18n found, a provider runs when something needs what it registers, or when the app boots. A server boots, so in production without SMTP_ADDRESS the server stops before taking a request:

config/providers/mailers.rb:16:in 'block (2 levels) in <top (required)>': SMTP_ADDRESS is not set: there is nowhere to hand the mail (ArgumentError)

The rake task that creates accounts only prepares the app. Nothing asks for the delivery method until the account exists and the email is on its way, so the same refusal arrives one step late: the account is created, the email is not sent, and the task aborts.

Development has the same shape when nothing listens on the SMTP port, as pointing the task at a closed one with SMTP_PORT=1 shows. The connection error is not a Net::SMTPError, the only exception the SMTP delivery turns into a failed result, so it escapes from deliver:

rake aborted!
Errno::ECONNREFUSED: Connection refused - connect(2) for "localhost" port 1 (Errno::ECONNREFUSED)

Here too the account was created before the email failed, but at least the error lands in front of whoever ran the task. A server that answers and rejects the message is quieter. That rejection is a Net::SMTPError, so it comes back as a failed result, and the task never looks at the result: it prints Created ... and exits normally, with an account whose owner was never told where to sign in. The companion app leaves it that way; it gets no new features after this series.

Three providers

The app has met three of them now. The first was a configuration I put in a provider because the word sounded like an initializer, and it never ran under the specs; the post on i18n tells that one. The second configures Hanami’s own i18n provider and hangs one hook on its start. The mail provider replaces Hanami’s entirely.

The first one registered nothing, so under the specs nobody ever started it. The mail provider registers a delivery method, and its refusal reaches each process when that process first needs one: the server at boot, the rake task at its first email, after the insert. A provider can also be started by name, and Hanami.app.start(:mailers) at the top of the task raises the same error before any account exists.

This state of the app is tagged 10-provider-not-initializer.

Comments, questions, or just a reaction?

Send an email to ~bounga/bounga.org-discuss@lists.sr.ht. It is public and archived, so other readers can follow along and answer too.