How To Conditionally Send Emails With Rails ActionMailer

Posted by Weston Ganger on September 01, 2016

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: "NoReply@MySite.com"

  # 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:

Posted in Rails and Tagged with rails action_mailer 

Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts