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

Sender & Recipient

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.

  1. module Mailers
  2. class Welcome
  3. include Hanami::Mailer
  4. from 'noreply@bookshelf.org'
  5. to 'user@example.com'
  6. subject 'Welcome to Bookshelf'
  7. end
  8. end

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.

  1. module Mailers
  2. class Welcome
  3. include Hanami::Mailer
  4. from 'noreply@bookshelf.org'
  5. to :recipient
  6. subject :subject
  7. private
  8. def recipient
  9. user.email
  10. end
  11. def subject
  12. "Welcome #{ user.name }!"
  13. end
  14. end
  15. end

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.

Locals

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.

  1. u = User.new(name: 'Luca', email: 'luca@example.com')
  2. 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.

Scope

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

  1. # lib/bookshelf/mailers/welcome.rb
  2. module Mailers
  3. class Welcome
  4. include Hanami::Mailer
  5. # ...
  6. def greeting
  7. "Ahoy"
  8. end
  9. end
  10. end
  1. # lib/bookshelf/mailers/templates/welcome.html.erb
  2. <h2><%= greeting %></h2>