Basic Usage

In the previous section, we generated a mailer, let's use it.


Firstly, we need to specify sender and recipient(s) and the subject of the email. For this purpose a mailer exposes three mandatory methods: .from, .to, .subject and two optional: .cc, .bcc.

They all accept a string, but .to can also accept an array of strings in order to set multiple recipients.

class Mailers::Welcome
  include Hanami::Mailer

  from    ''
  to      ''
  subject 'Welcome to Bookshelf'

Both .from and .to MUST be specified when we deliver an email.

An email subject isn't mandatory, but it's a good practice to set this information.

You may have noticed that have a hardcoded value can be useful to set the sender, but it doesn't work well for the rest of the details.

If you pass a symbol as an argument, it will be interpreted as a method that we want to use for that information.

class Mailers::Welcome
  include Hanami::Mailer

  from    ''
  to      :recipient
  subject :subject


  def recipient

  def subject
    "Welcome #{ }!"

There is NOT a convention between the name of the methods and their corresponding DSL.

We suggest to use always private methods for these informations, unless they need to be available from the templates.



In the previous section, we have referenced an user variable, where does it come from? Similarly to a view, a mailer can have a set of locals that can be passed as an argument in order to make them available during the rendering.

u = 'Luca', email: '')
Mailers::Welcome.deliver(user: u)

We can specify as many locals as we want, the key that we use for each of them it's the same that we use to reference that object. For instance, we passed :user key, and we can use user in the mailer and its associated templates.

The following keys for locals are RESERVED: :format and :charset.


All the public methods defined in a mailer are accessible from the templates:

# lib/bookshelf/mailers/welcome.rb
class Mailers::Welcome
  include Hanami::Mailer

  # ...

  def greeting
# lib/bookshelf/mailers/templates/welcome.html.erb
<h2><%= greeting %></h2>

Looking for Lotus? We renamed the project and it's now called Hanami. Read the announcement.