Can I specify a different recipient for an ActionMailer email based on the environment?
-
20-09-2019 - |
Question
I'm wondering if it's possible to configure a Rails email derived from ActionMailer to send to a different recipient based on the environment. For example, for development I'd like it to send mail to my personal email so I don't clog up our company email account with "Testing" emails; for production however I want it to use the real address.
How can I achieve this?
Solution
By default the development environment isn't setup to actually send emails (it just logs them).
Setting up alternate accounts can be done in many different ways. You can either use some logic in your mailer like so...
recipients (Rails.env.production? ? "email@company.com" : "test@non-company.org")
Or you can define the recipient as a constant in the environment files like so:
/config/environment/production.rb
EMAIL_RECIPIENT = "email@company.com"
/config/environment/development.rb
EMAIL_RECIPIENT = "test@non-company.org"
and then use the constant in your mailer. example:
recipients EMAIL_RECIPIENT
OTHER TIPS
The mail_safe plugin might be a little over kill. A simple initializer will do
Rails 2.x
if Rails.env == 'development'
class ActionMailer::Base
def create_mail_with_overriding_recipients
mail = create_mail_without_overriding_recipients
mail.to = "mail@example.com"
mail
end
alias_method_chain :create_mail, :overriding_recipients
end
end
Rails 3.x
if Rails.env == 'development'
class OverrideMailReciptient
def self.delivering_email(mail)
mail.to = "mail@example.com"
end
end
ActionMailer::Base.register_interceptor(OverrideMailReciptient)
end
Also, there are several plugins that do this. The best one that I've found of the three I looked at was mail_safe.