How to preview emails with ActionMailer::Preview on Rails

We know how it's a pain to test e-mails in our dev environment. Thinking of it, on Rails 4.1, the ActionMailer::Preview was released, making it possible to view e-mails without actually sending them. Let's learn how to use this tool.

First of all, we need to create a new mailer in our project.

rails generate mailer Welcome
Running via Spring preloader in process 5087
      create  app/mailers/welcome_mailer.rb
      invoke  erb
      create    app/views/welcome_mailer
      invoke  test_unit
      create    test/mailers/welcome_mailer_test.rb
      create    test/mailers/previews/welcome_mailer_preview.rb

It's possible to see that Rails created to files inside test filter: _test/mailers/welcome_mailertest.rb and _test/mailers/previews/welcome_mailerpreview.rb. In our case, we are going to use _test/mailers/previews/welcome_mailerpreview.rb to preview our templates.

Now let's create a method inside WelcomeMailer that will be responsible for sending a welcome message to users that signup in our system, assuming we have a model User with an e-mail attribute. To do that, we need to open the file _app/mailers/welcomemailer.rb

class WelcomeMailer < ApplicationMailer

  def send_welcome_email(user)
    @user = user
    mail({
      to: user.email,
      from: 'eu@mauricioackermann.com.br',
      subject: 'Seja bem-vindo ao sistema Maurício Ackermann'
      })
  end

end

Since WelcomeMailer is inheriting from ApplicationMailer, he will use the mailer default layout

class ApplicationMailer < ActionMailer::Base
  default from: 'from@example.com'
  layout 'mailer'
end

app/layouts/mailer.html.erb

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style>
      /* Email styles need to be inline */
    </style>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

At last, we need to create an e-mail template. Let's create a file send_welcome_email.html.erb inside the folder _app/views/welcomemailer, which will be our e-mail view.

<p>Hello, <%= @user.name %></p>
<p><strong>Thank you</strong> for registering in our system!</p>

Now that we have our mailer and template done let's test it. All e-mail previews are in test/mailers/previews. Open the file created by our generator, _welcome_mailerpreview.html.erb.

class WelcomeMailerPreview < ActionMailer::Preview

  def send_welcome_email
    WelcomeMailer.send_welcome_email(User.new(name: 'Maurício Ackermann', email: 'eu@mauricioackermann.com.br'))
  end

end

Now to visualize the e-mail, we start the server and access the link localhost:3000/rails/mailers/welcome_mailer..

Did you know about this Rails feature? I hope this post helps you debugging your projects