如何配置 ActionMailer 以使用 SendGrid 的 V2 API?

问题描述

自 2021 年 1 月 20 日起,将不再支持使用用户名和密码进行身份验证。如何配置我的 rails 应用程序以使用 api 密钥进行身份验证?我正在使用 Heroku。

解决方法

首先,登录您的 SendGrid 帐户并生成新的 api 密钥。为您的应用程序授予适当的权限。 https://app.sendgrid.com/settings/api_keys

然后编辑您的 config/environments/production.rb 文件。

来自这样的事情:

  ActionMailer::Base.smtp_settings = {
    :address => 'smtp.sendgrid.net',:port => '587',:authentication => :plain,:user_name => ENV['SENDGRID_USER_NAME'],:password => ENV['SENDGRID_PASSWORD'],:domain => 'heroku.com',:enable_starttls_auto => true}

为此:

  ActionMailer::Base.smtp_settings = {
    :address => 'smtp.sendgrid.net',:user_name => 'apikey',:password => ENV['SENDGRID_API_KEY'],:enable_starttls_auto => true}

请注意,我们将用户名更改为“apikey”,并将密码更改为存储在环境变量中的 api 密钥。