# 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_mailer_test.rb_ and _test/mailers/previews/welcome_mailer_preview.rb_. In our case, we are going to use **_test/mailers/previews/welcome_mailer_preview.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/welcome_mailer.rb_

```ruby
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
```ruby
class ApplicationMailer < ActionMailer::Base
  default from: 'from@example.com'
  layout 'mailer'
end
```

_app/layouts/mailer.html.erb_
```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/welcome_mailer_, which will be our e-mail view.

```erb
<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_mailer_preview.html.erb_**.
```ruby
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**
http://localhost:3000/rails/mailers/welcome_mailer/send_welcome_email

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