Hartl Ruby on Rails 教程 - Sendgrid 在生产环境中不发送电子邮件



更新:我通过heroku的网站访问我的应用程序来发送电子邮件,但当我在cloud9ide的生产服务器上运行该应用程序时,它仍然失败。这正常吗?这是教程希望我做的方式吗?

在Michael Hartl的Ruby on Rails教程的第11章中,您被要求在部署模式下使用您控制的电子邮件注册示例应用程序,并检查您的电子邮件帐户是否有帐户激活电子邮件。我没有收到任何电子邮件,heroku的sendgrid插件报告没有发送电子邮件请求。然而,在cloud 9 ide puma服务器控制台中,它报告电子邮件是以正确的格式发送到正确的地址的,我可以从控制台中检索激活令牌和电子邮件地址。我不确定我做错了什么。希望所有相关的代码都包含在下面。请帮忙。

实际上,我去了示例应用程序网站,点击注册,然后等待电子邮件。这不是Hartl所说的"在生产中注册一个新帐户"的意思吗?

config/enenvironment.rb:

# Load the Rails application.
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
#Sendgrid configurations from their website
ActionMailer::Base.smtp_settings = {
:user_name =>ENV['SENDGRID_USERNAME'],
:password  =>ENV['SENDGRID_PASSWORD'],
:domain    => 'heroku.com',
:address   => 'smtp.sendgrid.net',
:port      => 587,
:authentication => :plain,
:enable_starttls_auto => true
}

mailers/application_mailer:

class ApplicationMailer < ActionMailer::Base
default from: 'noreply@example.com'
layout 'mailer'
end

环境/生产.rb:

config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
host = 'gentle-lake-88943.herokuapp.com'
config.action_mailer.default_url_options = { host: host }
ActionMailer::Base.smtp_settings = {
:address        => 'smtp.sendgrid.net',
:port           => '587',
:authentication => :plain,
:user_name      => ENV['SENDGRID_USERNAME'],
:password       => ENV['SENDGRID_PASSWORD'],
:domain         => 'heroku.com',
:enable_starttls_auto => true
}

users_controller.rb:

def create
@user = User.new(user_params)
if @user.save
@user.send_activation_email
flash[:info] = "Please check your email to activate your account"
redirect_to root_url
else 
render 'new'
end
end

user.rb:

def activate
update_columns(activated: true, activated_at: Time.zone.now)
end
def send_activation_email
UserMailer.account_activation(self).deliver_now
end

routes.rb:

resources :account_activations, only: [:edit]

我刚刚解决了本教程的问题。我最初的问题是我没有正确地写变量名。我已经检查了我的代码并修复了它。正如教程所说,我的应用程序现在运行良好。

正如Igor在最后一次回答中所说,你不需要config/enenvironments.rb中的任何特殊代码,所以如果你保留它,你应该删除它。

使用heroku run printenv检查Heroku中的环境变量。如果这些都是正确的,请尝试BAD方法,就像测试一样:用sendgrid的用户名和密码替换ENV['SENDGRID_xxx']

感谢弥敦道

最新更新