Email delivery in test environments

ActionMailer is a really nice framework for sending email. It is wonderful to be able to set delivery to test mode and have messages stuck in an array instead of being delivered. What do you do in a staging environment where you actually want to see the messages, but don’t want them sent to the actual recipients entered? I’ll show you a simple way to solve this problem.

Our solution to this problem is to send all emails to a single address. This allows us to view the email and click the links without worrying about email messages from the test system polluting our inboxes. The only question is how do we acheive this?

Luckily, ActionMailer itself is pretty easy code to read. By tracing the path of the delivery methods, I came to a point where it calls perform_delivery_#{delivery_method}. How nice is that? The configuration directive config.action_mailer.delivery_method = :test means that perform_delivery_test will be called whenever an email is going to be sent in that environment. That means all we need to do is to create our own perform delivery method and set that configuration option. A few minutes later, we had:

module ActionMailer
  class Base
  def perform_delivery_staging(mail)
      mail.to="staging@elevatedrails.com" 
      mail.cc="" 
      mail.bcc="" 
      perform_delivery_sendmail(mail)
    end
  end
end

Now, if you set config.action_mailer.delivery_method = :staging in an environment, all messages will be sent to staging@elevatedrails.com. What a simple solution!

Posted by Mike Mangino on Wednesday, October 25, 2006