Conditionally Send Emails With Rails ActionMailer

Posted By Weston Ganger

One trick with ActionMailer is that you can conditionally send emails. This is great if you need to disable emails during a certain time period or in the staging environment.

This is different than disabling deliveries in the environment configs because this method will still send all of the emails you want it to.

You can apply this to any specific controller but I usually use it on a parent class such as ApplicationMailer, and making all applicable mailers inherit from this class. By doing it this way Devise, Exception Notifier, etc. emails will still send because they do not inherit from ApplicationMailer.

class ApplicationController < ActionController::Base
  default from: ""

  # This line for Rails 3 only, Rails 4+ doesn't need this
  include AbstractController::Callbacks

  before_action :check_before_sending


  def check_before_sending
    if Rails.env.staging?
      mail.perform_deliveries = false

Just make sure your Mailer classes inherit from ApplicationMailer and the before_action will be applied.

Related External Links:

Article Topic:Software Development - Ruby / Rails

Date:September 01, 2016