mdv.io

💌 Adding your environment name to ActionMailer subjects

July 10, 2020

Wouldn’t it be nice to know which emails came from your staging app versus your production app? If you’re using Rails and ActionMailer, it’s a breeze.

Just open up app/mailers/application_mailer.rb and add the following after_action block:

# app/mailers/application_mailer.rb

class ApplicationMailer < ActionMailer::Base
  # ...

  after_action do
    mail.subject.prepend(ENV['MAILER_SUBJECT_PREFIX']) if ENV["MAILER_SUBJECT_PREFIX"]
  end
end

This will take whatever you have set in your environment as MAILER_SUBJECT_PREFIX and prepend it to your subject line.

For example, I use MAILER_SUBJECT_PREFIX="[STAGING] ”, and my Daily stats email subject line changes from:

  • from: 📈 Daily stats for July 10, 2020
  • to: [STAGING] 📈 Daily stats for July 10, 2020

Keep in mind, you don’t want to set this environment variable in production!

Alternatively, you can do this without Environment variables

Sometimes you don’t want to use Environment Variables, which is fine. Just modify the code above to look like:

# app/mailers/application_mailer.rb

class ApplicationMailer < ActionMailer::Base
  # ...

  after_action do
    mail.subject.prepend("[STAGING] ") if Rails.env.staging?
  end
end

And there you have it. Happy mailing!