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?
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.
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With