Rails ActionMailer忽略了environment.rb中的设置。

8
我将我的ActionMailer配置放在config/environment.rb文件中,如下所示:
MyApp::Application.initialize!
MyApp::Application.configure do

  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
      address: "smtp.elasticemail.com",
      port: 2525,
      domain: "myapp.com",
      authentication: "plain",
      user_name: "my_username",
      password: "my_password",
      enable_starttls_auto: true
  }

end

我理解的正确方法是配置所有环境都适用的设置。

在开发中,这个方法很好用,但当我部署到我的暂存服务器时(使用自定义的config/environments/staging.rb配置文件),发送邮件时出现“连接拒绝”错误。staging.rb文件中没有任何与邮件相关的设置。

所以我使用 RAILS_ENV=staging rails c 命令启动暂存环境下的控制台,输出 "puts Rails.application.config.action_mailer" 后,显示我在 environment.rb 文件中设置的内容确实生效了。但由于某种原因,ActionMailer并未使用这些设置。

经过实验,我发现将配置直接复制到staging.rb文件中可以解决问题。为什么需要这样做?如果rails控制台显示设置已生效,为什么ActionMailer不使用这些设置呢?

进一步挖掘后,我发现我的 mailer 类的 delivery_method 没有按预期设置:

MyMailer.foo(Person.find(1)).delivery_method

 => #<Mail::SMTP:0x0000000370d4d0 @settings={:address=>"localhost", :port=>25, :domain=>"localhost.localdomain", :user_name=>nil, :password=>nil, :authentication=>nil, :enable_starttls_auto=>true, :openssl_verify_mode=>nil, :ssl=>nil, :tls=>nil}> 
1个回答

13

放置

MyApp::Application.configure do

  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
      address: "smtp.elasticemail.com",
      port: 2525,
      domain: "myapp.com",
      authentication: "plain",
      user_name: "my_username",
      password: "my_password",
      enable_starttls_auto: true
  }

end

MyApp::Application.initialize! 之前


4
我很想看看Stackoverflow SQL日志,以了解我提问和你回答(并解决)的时间差...必须小于30秒。 - George Armhold
很棒的问题!很好的答案!为我解决了一个棘手的问题。 - thisfeller

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接