How to preview emails with ActionMailer::Preview on Rails

Subscribe to my newsletter and never miss my upcoming articles

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
      from: '',
      subject: 'Seja bem-vindo ao sistema Maurício Ackermann'


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

class ApplicationMailer < ActionMailer::Base
  default from: ''
  layout 'mailer'


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

    <%= yield %>

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, <%= %></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( 'Maurício Ackermann', email: ''))


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

No Comments Yet