Rails 4 Sendgrid集成出错-未经身份验证的发件人不允许。

7

我已在Rails 4服务器上集成了Sendgrid设置。这些设置在开发环境下运行良好,但在生产环境中会出现错误。

Net::SMTPFatalError (550 Cannot receive from specified address <simmi@mydomain.com>: Unauthenticated senders not allowed)

config/initializers/email_setup.rb

ActionMailer::Base.smtp_settings = {
   :address              => "smtp.sendgrid.net",
   :domain               => DOMAIN,
   :user_name            => ENV['SENDGRID_USERNAME'],
   :password             => ENV['SENDGRID_PASSWORD'],
   :authentication       => "plain",
   :enable_starttls_auto => true
}

config/initializers/devise.rb

config.mailer_sender = 'simmi@mydomain.com'

config/environments/production.rb

# Default URL
config.action_mailer.default_url_options = { host: 'mysite.mydomain.com' }

DOMAIN = 'mysite.mydomain.com'
4个回答

10
根据sendgrid支持团队的说法,出现此错误是因为用户名或密码不正确。我尝试通过telnet手动登录smtp服务器,结果成功了。
在我的服务器命令行上,我按照以下步骤进行操作:
telnet smtp.sendgrid.net 587
EHLO
AUTH LOGIN
Enter username in Base64
Enter password in Base64

将文本转换为Base64的链接 - http://www.opinionatedgeek.com/dotnet/tools/base64encode/

在我的生产环境中,环境变量似乎无法正常工作。作为解决方法,我尝试直接添加用户名和密码,这样做起来就可以了。


密码现在是在设置中生成的API密钥。 - Robert

4
我也遇到了同样的问题,通过添加以下内容解决了它:
config/environment.rb
ActionMailer::Base.smtp_settings = {
  :address              => "smtp.sendgrid.net",
  :domain               => DOMAIN,
  :user_name            => ENV['SENDGRID_USERNAME'],
  :password             => ENV['SENDGRID_PASSWORD'],
  :authentication       => "plain",
  :enable_starttls_auto => true
}
ActionMailer::Base.default_url_options = { host: 'mysite.mydomain.com' }

config/application.rb

ActionMailer::Base.delivery_method = :smtp

如果你想在开发模式下测试发送邮件,letter_opener gem非常有用。如果你想覆盖letter_opener,请添加以下配置

config/environments/development.rb

ActionMailer::Base.delivery_method= :letter_opener

同时在 ActionMailer::Base.smtp_settings 下添加端口。


1
你可能是在尝试初始化邮件服务器之后再加载环境变量。你可以在加载变量后直接进行初始化以确保它们的存在。
设置一个配置文件,包含用户名和密码变量:
# config/mailer.yml
production:
   SENDGRID_USERNAME: 'username'
   SENDGRID_PASSWORD: 'password'

设置一个初始化文件:

# config/initializers/mailer.rb
if Rails.env.production?
  config_path = File.expand_path(Rails.root.to_s + '/config/mailer.yml')
  if File.exists? config_path
    ENV.update YAML.load_file(config_path)[Rails.env]
  end

  ActionMailer::Base.smtp_settings = {
    :address        => 'smtp.sendgrid.net',
    :port           => '587',
    :authentication => :plain,
    :user_name      => ENV["SENDGRID_USERNAME"],
    :password       => ENV["SENDGRID_PASSWORD"],
    :domain         => "yourdomain",
  }
end

-2

如果您的生产环境是Heroku:

登录您的Heroku帐户并选择应用程序。在“设置”下,单击“显示配置变量”按钮。输入您的sendgrid密钥和值对,然后提交。运行:heroku restart


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