【问题标题】:How to avoid a 500 Internal Server Error when using the Rails ActionMailer on Heroku在 Heroku 上使用 Rails ActionMailer 时如何避免 500 内部服务器错误
【发布时间】:2019-09-08 15:52:42
【问题描述】:

我正在尝试在我的 Web 应用程序中注册时向用户发送一封电子邮件,该应用程序是在后端使用 Rails 构建的,在前端使用 React-Redux 构建的。在本地服务器上进行测试时,我使用了一个名为 letter_opener 的 gem,一切似乎都运行良好。当我在 Heroku 上进行现场测试时,我得到了 500 错误,我不确定出了什么问题。

我尝试阅读 ActionMailer 文档,但似乎没有提到任何此类问题。

UserMailer中的方法:

def welcome_email(user)
    @user = user
    mail(to: @user.email, subject: "Welcome")
end

UsersController中的相关代码:

def create
   # ...
   email = UserMailer.welcome_email(@user)
   email.deliver_now   # This line throws the error
   # ...
end

Heroku 日志中的错误:

Errno::ECONNREFUSED (Connection refused - connect(2) for "localhost" port 25):

我希望电子邮件能够送达,或者至少会有更多信息性的错误消息。我不确定为什么 Rails 会查看 localhost 的 25 端口。

【问题讨论】:

    标签: ruby-on-rails heroku


    【解决方案1】:

    我不确定 Rails 为什么会查看 localhost 的 25 端口。

    ActionMailer defaults to localhost:25,你可能只是改变了你的开发配置。

    Errno::ECONNREFUSED(连接被拒绝 - “localhost”端口 25 的连接(2))

    Heroku 不提供 SMTP 服务器,localhost 上肯定不会有。使用 an email addon 或您选择的其他第三方邮件服务。

    您可能必须修改 config/environments/production.rb 才能使用您选择的任何邮件服务。

    【讨论】:

      【解决方案2】:

      Chris 是对的,Heroku 不提供 SMTP 服务器,您必须使用插件。我将进一步补充您如何继续使用sendgrid 插件,它在很大程度上是免费的。

      首先,转到您的 Heroku 应用 -> 启用 sendgrid 插件。然后,您将获得 sendgrid 凭据。保护他们的安全。

      在你的config/environments/production.rb 添加:

      config.action_mailer.delivery_method = :smtp
      config.action_mailer.default_url_options = { host: "your-domain.com", protocol: 'https' }
      

      然后在您的config/environment.rb 文件中添加:

      ...
      # Initialize the Rails application.
      Rails.application.initialize!
      
      # Add sendgrid support
      if Rails.env.production?
        ActionMailer::Base.smtp_settings = {
          :user_name => "sendgrid_username",
          :password => "sendgrid_password",
          :domain => "your-domain.com",
          :address => "sendgrid_hostname",
          :port => 3000, # sendgrid_port
          :authentication => :plain,
          :enable_starttls_auto => true
        }
      end
      

      根据需要更改上述凭据。还可以考虑为上述凭据使用ENV 变量。

      【讨论】:

      • 谢谢,成功了!
      猜你喜欢
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      相关资源
      最近更新 更多