Rails 5 应用程序无法发送 sendgrid 电子邮件(Cloud 9 和 Heroku)

kas*_*ar9 3 ruby-on-rails heroku mailer

我已经检查了很多关于它的帖子,但仍然找不到解决方案..我认为它在部署中工作,但不,这些电子邮件没有发送..我只是将它们放入控制台。

我检查了我的 sendgrid 凭据,我使用 dotenv 添加了全局变量,所以我的代码可能有问题。

我还尝试使用该代码直接发送电子邮件:

require 'sendgrid-ruby'
include SendGrid

from = Email.new(email: 'test@example.com')
to = Email.new(email: 'test@example.com')
subject = 'Sending with SendGrid is Fun'
content = Content.new(type: 'text/plain', value: 'and easy to do anywhere, 
even with Ruby')
mail = Mail.new(from, subject, to, content)

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
response = sg.client.mail._('send').post(request_body: mail.to_json)
puts response.status_code
puts response.body
puts response.parsed_body
puts response.headers
Run Code Online (Sandbox Code Playgroud)

没有运气:

puts response.status_code
400
 => nil 
2.3.4 :016 > puts response.body
{"errors":[{"message":"Invalid type. Expected: object, given: string.","field":"(root)","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#-Request-Body-Parameters"}]}
 => nil 
 puts response.parsed_body
{:errors=>[{:message=>"Invalid type. Expected: object, given: string.", :field=>"(root)", :help=>"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#-Request-Body-Parameters"}]}
2.3.4 :017 > puts response.headers
{"server"=>["nginx"], "date"=>["Wed, 04 Apr 2018 17:43:43 GMT"], "content-type"=>["application/json"], "content-length"=>["191"], "connection"=>["close"], "access-control-allow-origin"=>["https://sendgrid.api-docs.io"], "access-control-allow-methods"=>["POST"], "access-control-allow-headers"=>["Authorization, Content-Type, On-behalf-of, x-sg-elas-acl"], "access-control-max-age"=>["600"], "x-no-cors-reason"=>["https://sendgrid.com/docs/Classroom/Basics/API/cors.html"]}
 => nil
Run Code Online (Sandbox Code Playgroud)

我的朋友从他的计算机发送了相同的代码并且它正在工作......不知道该怎么做。我在 Cloud9 上工作,也许这就是问题所在..我在编码方面没有太多经验,所以我真的很感谢你们的帮助:)

我的作品.rb

Rails.application.configure do

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
    }
# Code is not reloaded between requests.

config.cache_classes = true
config.eager_load = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { :host => 
 'myapp.herokuapp.com', :protocol => 'https'}

# Full error reports are disabled and caching is turned on.

config.consider_all_requests_local       = false
config.action_controller.perform_caching = true

# Attempt to read encrypted secrets from `config/secrets.yml.enc`.

# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or

# `config/secrets.yml.key`.

 config.read_encrypted_secrets = true

# Disable serving static files from the `/public` folder by default since

# Apache or NGINX already handles this.

config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?

# Compress JavaScripts and CSS.

config.assets.js_compressor = :uglifier

# config.assets.css_compressor = :sass

# Do not fallback to assets pipeline if a precompiled asset is missed.

config.assets.compile = false
Run Code Online (Sandbox Code Playgroud)

我的发展.rb

Rails.application.configure do

config.cache_classes = false

# Do not eager load code on boot.

config.eager_load = false
config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = { :host => 
'https://myapp.c9users.io'}

# Show full error reports.

config.consider_all_requests_local = true

# Enable/disable caching. By default caching is disabled.

if Rails.root.join('tmp/caching-dev.txt').exist?
    config.action_controller.perform_caching = true

    config.cache_store = :memory_store
    config.public_file_server.headers = {
      'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}"
    }
else
    config.action_controller.perform_caching = false

    config.cache_store = :null_store
end
Run Code Online (Sandbox Code Playgroud)

环境.rb

require_relative 'application'

Rails.application.initialize!


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
}
Run Code Online (Sandbox Code Playgroud)

And*_*ter 5

SendGrid API 非常脆弱,在 Rails 中更是如此。您可能会收到该错误,因为您正在使用Mail而不是SendGrid::Mail. SendGrid 提供的示例代码存在此缺陷,大概是因为他们在 Ruby 脚本而不是 Rails 环境中对其进行了测试。Mail已经是 Rails 中的一个现有类,并且 Rails 做了一件奇怪的事情,即所有内容都会自动导入到任何地方,这与正常的 Ruby 代码不同。

将相关行更改为如下所示:

mail = SendGrid::Mail.new(from, subject, to, Content.new(type: 'text/plain', value: 'hi this is a test email'))
mail.add_content Content.new(type: 'text/html', value: '<h1>test email</h1><p>hi</p>')
Run Code Online (Sandbox Code Playgroud)

另请注意,如果您想同时发送纯文本和 HTML 正文,则必须严格按照顺序执行。

如果您不将任何内容传递到该new方法中,而只是调用add_content两次,您将收到另一个无意义的Invalid type. Expected: object, given: string错误,因为构造函数将添加nil到内容列表中。

如果将 HTML 内容传递到构造函数并调用add_content纯文本内容,您将收到一个不同的错误,指出必须首先添加纯文本内容。

当您遇到这些错误时,通常有用的做法是打印出来mail.to_json。这将使您更深入地了解代码发送到 SendGrid 的内容。