Developing email templates and sending a new mail every time to view a change is very inefficient and painful. Rails comes in rescue again. Rails 4.1 implemented a feature called Mailer Preview. With mailer preview, you can view the changes in your browser just like any other page template.

So, How do we do this? First you've to have a Mailer. For example purpose, let's create a Mailer called WelcomeMailer inside app/mailers. Also create a view for it in app/views/welcome_mailer/.

app/mailers/welcome_mailer.rb

class WelcomeMailer < ActionMailer::Base
  def hello
    mail(to: '[email protected]', subject: 'Welcome to Awesomeness')
  end
end

And app/views/welcome_mailer/hello.html

<h1>Hello Mister</h1>
<p>Welcome to our awesome website https://www.babar.im/</p>

<p>Have your wish full filled</p>    

Now let's create the preview. Create mailers/previews directory inside your test directory. (If you're using Rspec, create it in the spec directory). Now inside that directory, create a new file called welcome_preview.rb and fill it like this:

class WelcomePreview < ActionMailer::Preview
  def hello
    WelcomeMailer.hello
  end
end

Save it, start your rails development server (rails s) and hit browser with URL: http://localhost:3000/rails/mailers/welcome/hello, and, you're good to go!

If you have both text and HTML template, we can switch the view as well from this page. Now add all the mailers in the preview and develop/design templates more easily.

Happy Hacking!




What's on your mind?


371 Comments