我在Heroku上,开发环境下无法发送电子邮件,但在生产环境下可以正常发送。我想在Heroku上运行一个单独的分离实例,但不希望发送电子邮件(只记录日志)。
我在Heroku上,开发环境下无法发送电子邮件,但在生产环境下可以正常发送。我想在Heroku上运行一个单独的分离实例,但不希望发送电子邮件(只记录日志)。
在test.rb中的这行代码告诉ActionMailer不要发送电子邮件:
config.action_mailer.delivery_method = :test
相反,它们会被累积在ActionMailer::Base.deliveries数组中。
你需要为应用程序设置一个分段环境,并配置Heroku在你的分段实例上使用该环境。
使用 Mail gem 的应用程序(包括 rails >= 3.0 项目)可以使用 safety_mailer gem。指定允许发送电子邮件的域名(或一组域名或电子邮件地址中的魔术词),对于所有其他域名的电子邮件将被静默丢弃。
https://github.com/cluesque/safety_mailer
将该 gem 添加到您的 Gemfile
,并指定要包含它的组(可能不是生产环境)。
gem "safety_mailer", :group => :development
别忘了执行bundle install
命令来安装依赖包。
在你的环境文件config/environments/development.rb
中进行配置,包括一些正则表达式。
config.action_mailer.delivery_method = :safety_mailer
config.action_mailer.safety_mailer_settings = {
allowed_matchers: [ /mydomain.com/, /mytestacct@gmail.com/, /super_secret_test/ ],
delivery_method: :smtp,
delivery_method_settings: {
:address => "smtp.mydomain.com",
:port => 25,
:domain => "mydomain.com",
:authentication => :plain,
:user_name => "mydomain_mailer@mydomain.com",
:password => "password"
}
}
现在,发送到 anyone@mydomain.com、mytestacct@gmail.com、bob+super_secret_test@yahoo.com 的电子邮件都会被发送,而发送到其他收件人(比如你复制到测试服务器的生产数据库中的真实用户)的电子邮件将被抑制。
您可能会对mailtrap.io感兴趣(免责声明:我与该产品有关联)。它是在开发和生产中测试电子邮件传递的完美工具。您只需要将mailtrap.io设置为暂存环境配置中的smtp服务器即可:
config.action_mailer.smtp_settings = {
:address => "mailtrap.io",
:port => 2525,
:authentication => :plain,
:user_name => "LOGIN",
:password => "PASSWORD"
}
在这种情况下,您所有在测试环境中发送的测试邮件都将被存储在Mailtrap中以供查看和共享。但是没有一封邮件会发送到真实地址。您也可以在开发中使用它。 顺便说一句——它完全免费!
将此代码放入您的environment.rb文件中
config.action_mailer.delivery_method = :test
我认为有一个:log选项,但我没有尝试过。它应该停止向邮件服务器发送邮件。
environments/staging.rb
文件中,而不是全局的 environment.rb
文件中。 - Robert Speicher我看到有人建议使用 Mailtrap.io。一个很好的替代品是 Debug Mail。使用起来非常简单。
If you want a convenient way of receiving emails for debugging, etc. I recommend https://github.com/fgrehm/letter_opener_web
, which will save emails locally, and provide an URL to browse emails that were sent. No email is sent outside, and you can very conveniently see the output in your browser
If you want to be able to open email files with your email clients, you should choose a :file
adapter for ActionMailer (configure in config/environments/your_env.rb
)
If you want a real production-like environment, I'd suggest to configure an email interceptor that would rewrite the TO/CC/BCC to a real mailbox of your choice, this way you can keep and test your original ActionMailer adapter
if Rails.env.staging?
class TestEmailsInterceptor
def self.delivering_email(mail)
mail.to = ['My Test Box <test-box@example.com>']
# remove bcc, cc, etc.
end
end
ActionMailer::Base.register_interceptor(TestEmailsInterceptor)
end