views:

124

answers:

3

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?

+3  A: 

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 protected]" : "[email protected]")

Or you can define the recipient as a constant in the environment files like so:

/config/environment/production.rb

EMAIL_RECIPIENT = "[email protected]"

/config/environment/development.rb

EMAIL_RECIPIENT = "[email protected]"

and then use the constant in your mailer. example:

recipients EMAIL_RECIPIENT
semanticart
Great, that should do it. Thanks!
Wayne M
A: 

Also, there are several plugins that do this. The best one that I've found of the three I looked at was mail_safe.

Joshua Born
+1  A: 

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 = "[email protected]"
      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 = "[email protected]"
    end
  end

  ActionMailer::Base.register_interceptor(OverrideMailReciptient)
end
Rob