Rails 4 Sendgrid integration giving error - Unauthenticated senders not allowed

无人久伴 提交于 2019-11-30 14:10:02

According to sendgrid support team, this error comes when username or password are incorrect. I tried logging manually into the smtp server through telnet and it was working.

On my server commandline, I followed these steps:

telnet smtp.sendgrid.net 587
EHLO
AUTH LOGIN
Enter username in Base64
Enter password in Base64

Link to convert text into Base64 - http://www.opinionatedgeek.com/dotnet/tools/base64encode/

The ENV variables were somehow not working on my production environment. As a workaround, I tried adding the username and password directly and it worked.

user1099939

I have also faced the same problem and fixed it by adding the following:

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

The letter_opener gem is very useful if you want to test sending emails in development mode. If you want to overwrite the letter_opener, add the following configuration

config/environments/development.rb

ActionMailer::Base.delivery_method= :letter_opener

And also add the port under ActionMailer::Base.smtp_settings.

You are probably loading your environment variables after you are trying to initialize your mailer. You can do the initialization directly after loading your variables to be sure that they exist.

Set up a config file with your username and password variables:

# config/mailer.yml
production:
   SENDGRID_USERNAME: 'username'
   SENDGRID_PASSWORD: 'password'

Set up an initializer file:

# 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

If your production environment is Heroku:

Login to your Heroku account and select the application. Under "Settings", click the "Reveal Config Vars" button. Enter in your sendgrid key and value pairs, then submit. Run: heroku restart.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!