12 Gems of Christmas #4 – mailcatcher and mail_view

2012-12-09

Surprise, today’s blog posting is a double header!

Testing email can be painful, verifying delivery and look and feel quickly becomes tedious. mailcatcher and mail_view are my go-to tools for dealing with email.

mailcatcher

With mailcatcher, you install the gem and then run the mailcatcher binary to start the mailcatcher daemon in the background. Now you have an SMTP server running on port 1025 and an inbox available at http://localhost:1080. I configured The Clymb Rails app to automatically use mailcatcher if it’s running:

# config/initializers/email.rb
begin
  sock = TCPSocket.new("localhost", 1025)
  sock.close
  catcher = true
rescue
  catcher = false
end

ActionMailer::Base.smtp_settings = if Rails.env.development? && catcher
  { :host => "localhost", :port => '1025', }
else
  { } # normal SMTP config
end

Now you can test email via http://localhost:1080 and not have to use gmail, hotmail, etc.

mail_view

mail_view is awesome for rapidly testing UI changes in email. The trick is to render the email as a webpage directly in your Rails app so you can see changes immediately with Cmd+R just like any normal webpage. You just need to set up the email to be rendered with some data; in our case we just pull random data from the database since we all work with production database snapshots.

class Preview < MailView
  def order_receipt
    cart = Cart.where(:state => 'pushed').order(:id).last
    Emails.order_receipt(cart.id)
  end
end

Of course, we need to mount the mail_view engine itself:

# config/routes.rb
mount MailPreview => 'mail_view' if Rails.env.development?

Now we can go to http://localhost:3000/mail_view/order_receipt and immediately see what our order_receipt email looks like, no email required!

With mailcatcher and mail_view at your side, email development and testing goes from tedious to stupendous! Tomorrow we’ll cover a gem designed to build better command line scripts in Ruby…