在开发环境中覆盖ActionMailer的邮件地址

在我的开发环境中,我在本地测试时使用生产数据库的副本。 出于测试和简单防止向真实用户发送测试/开发电子邮件的原因,在开发模式下覆盖邮件地址的最佳方法是什么?

我知道我可以在每个邮件程序中编写逻辑,但我有几个,将它们全部放在一个位置会很好。 我可以以某种方式覆盖mail()方法使:to参数始终指向我指定的电子邮件地址吗?

我认为最好的选择是使用像mailtrap.io这样的服务: http ://mailtrap.io或mailcatcher gem: https ://rubygems.org/gems/mailcatcher

我使用ActionMailer拦截器,因此在开发或测试环境中发送的所有邮件都被发送到同一地址。 像这样:

 # config/initializers/override_mail_recipient.rb if Rails.env.development? or Rails.env.test? class OverrideMailRecipient def self.delivering_email(mail) mail.to = 'to@example.com' end end ActionMailer::Base.register_interceptor(OverrideMailRecipient) end 

我喜欢做的是在开发环境中配置动作邮件程序以使用mailtrap 。

你可以做默认值

 class UserMailer < ActionMailer::Base default :to=> "to@example.com" end 

然后使地址成为方法中的一个选项。 这样它将默认为:to你设置。 我的另一个想法是多一点:

 class UserMailer < ActionMailer::Base attr_accessor :email_address def initialize if RAILS_ENV == "development" @email_address = "to@example.com" end end end 

这将要求您在代码中设置一个新地址,但每次在开发中都会被覆盖。