Intercepting Action Mailer Emails in Rails


Create an Interceptor Module

To intercept emails in specific environments such as development, testing, or staging, we need to write some logic to do so.

module MailInterceptor
  def self.delivering_email(message)
    # This will be the email that live emails will be sent to 
    message.to = ['your-email@mail.com']

    # Set the cc and bcc to be nil to avoid sending out real emails
    message.cc = nil
    message.bcc = nil

    # Change the from if you want a different from
    message.from = 'your-email@mail.com'

    # If you want to modify the subject, do so here
    message.subject = message.subject + 'Intercepted by XXXXXXX'
  end
end

Then in your initializers/action_mailer.rb, add the following snippet:

ActionMailer::Base.register_interceptor(MailInterceptor)

To limit per environment, use a guard clause on that same line.

Photo Credit: https://pixabay.com/illustrations/email-marketing-online-marketing-2362038/