简体   繁体   English

根据环境覆盖到ActionMailer中的字段

[英]Override to field in ActionMailer based on environment

I'm using Rails 4.2 want to override the to field for all ActionMailer mailers for a certain environment. 我使用的是Rails 4.2,它希望为特定环境的所有ActionMailer邮件覆盖to字段。 In this case I want to override the to field for all mailers used in Staging. 在这种情况下,我要覆盖暂存中使用的所有邮件的“收件人”字段。 My goal is for the staging environment to deliver mail exactly the same way as production, but to dump it all into a testing inbox. 我的目标是为登台环境提供与生产完全相同的邮件传递方式,但将其全部转储到测试收件箱中。

I know there are services that assist with this, but my goal is to use my production API for staging delivery as a thorough test. 我知道有一些服务可以对此提供帮助,但是我的目标是使用生产API进行阶段交付,作为一项全面的测试。

I'm hoping I can use a mixin or something to reset the to field before the mailer fires off. 我希望我可以在邮件发送者解雇之前使用mixin或其他方法将to字段重置为。

Not sure what version of Rails you are using, but you might consider using the new mail interceptors to accomplish this. 不确定使用的是哪个版本的Rails,但是您可以考虑使用新的邮件拦截器来完成此操作。

Main advantage is that it doesn't clutter your ActionMailer classes directly. 主要优点是它不会直接使您的ActionMailer类混乱。

http://guides.rubyonrails.org/action_mailer_basics.html#intercepting-emails http://guides.rubyonrails.org/action_mailer_basics.html#intercepting-emails

Copying their example: 复制他们的示例:

class SandboxEmailInterceptor
  def self.delivering_email(message)
    message.to = ['sandbox@example.com']
  end
end

config/initializers/sandbox_email_interceptor.rb: config / initializers / sandbox_email_interceptor.rb:

ActionMailer::Base.register_interceptor(SandboxEmailInterceptor) if Rails.env.staging?

The simplest way would be to check which environment is running and set the to field accordingly. 最简单的方法是检查正在运行的环境并相应地将to字段设置为。 For example, a simple password reset mailer might look something like: 例如,一个简单的密码重置邮件程序可能类似于:

class UserMailer < ActionMailer::Base
  default from: "support@example.com"

  def reset_password(user_id)
    @user = User.find(user_id)
    @url  = reset_password_users_url(token: @user.password_reset_token)

    mail(to: @user.email, subject: '[Example] Please reset your password')
  end
end

Now to check for the staging environment and route all of these emails to admin@example.com : 现在检查暂存环境并将所有这些电子邮件路由到admin@example.com

class UserMailer < ActionMailer::Base
  default from: "support@example.com"

  def reset_password(user_id)
    @user = User.find(user_id)
    @url  = reset_password_users_url(token: @user.password_reset_token)

    to = Rails.env.staging? ? 'admin@example.com' : @user.email
    mail(to: to, subject: '[Example] Please reset your password')
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM