Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect all outgoing emails to single address for testing

In Ruby on Rails, I'm in a situation where I'd like my application (in a particular testing environment) to intercept all outgoing emails generated by the application and instead send them to a different, testing address (maybe also modifying the body to say "Initially sent to: ...").

I see ActionMailer has some hooks to observe or intercept mail, but I don't want to spin my own solution if there's an easier way to do this. Suggestions?

like image 718
jrdioko Avatar asked Dec 08 '10 23:12

jrdioko


2 Answers

We're using the sanitize_email gem with much success. It sends all email to an address you specify and prepends the subject with the original recipient. It sounds like it does exactly what you want and has made QA-ing emails a breeze for us.

like image 113
semanticart Avatar answered Sep 19 '22 10:09

semanticart


Rails 3.0.9+

This is now very simple to do with Action Mailer interceptors.

Interceptors make it easy to alter the receiving address, subject, and other details of outgoing mail. Just define your interceptor, then register it in an init file.

lib/sandbox_mail_interceptor.rb

# Catches outgoing mail and redirects it to a safe email address.
module SandboxMailInterceptor

  def self.delivering_email( message )
    message.subject = "Initially sent to #{message.to}: #{message.subject}"
    message.to = [ ENV[ 'SANDBOX_EMAIL' ] ]
  end
end

config/init/mailers.rb

require Rails.root.join( 'lib', 'sandbox_mail_interceptor' )

if [ 'development', 'staging' ].include?( Rails.env )
  ActionMailer::Base.register_interceptor( SandboxMailInterceptor )
end

You can also unregister the interceptor at any time if, for example, you need to test the original email without the interceptor's interference.

Mail.unregister_interceptor( SandboxMailInterceptor )

# Test the original, unmodified email.

ActionMailer::Base.register_interceptor( SandboxMailInterceptor )
like image 43
februaryInk Avatar answered Sep 22 '22 10:09

februaryInk