0

我已经像这样设置了我的环境:

echo "export SENDGRID_API_KEY='xxxxxxxxx'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env

Sendgrid gem 已安装。

我尝试运行的代码:

require 'sendgrid-ruby'
include SendGrid
require 'json'

def hello_world
  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)

  #previous version
  #sg = SendGrid::API.new(api_key: ENV['xxxxxxx'])

  #current version
  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.headers
end

hello_world

但我收到以下错误:

no implicit conversion of nil into String

在这个文件里面:

/ruby/gems/2.4.0/gems/sendgrid-ruby-5.2.0/lib/sendgrid/client.rb:24:in

我无法弄清楚这里出了什么问题......

完整错误:

/Users/pimzonneveld/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/sendgrid-ruby-5.2.0/lib/sendgrid/client.rb:24:in `+': no implicit conversion of nil into String (TypeError)
    from /Users/pimzonneveld/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/sendgrid-ruby-5.2.0/lib/sendgrid/client.rb:24:in `initialize'
    from app/helpers/mail.rb:12:in `new'
    from app/helpers/mail.rb:12:in `hello_world'
    from app/helpers/mail.rb:19:in `<main>'
4

2 回答 2

2

您将 env 变量 ( xxxxxxxxx) 的值与其名称 ( SENDGRID_API_KEY) 混淆了。

在代码中设置 API 密钥时,请使用

  sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])

反而。

于 2018-04-17T11:16:48.580 回答
0

深是对的。/ruby/gems/2.4.0/gems/sendgrid-ruby-5.2.0/lib/sendgrid/client.rb:24:in 指

"Authorization": "Bearer ' + @api_key + '",

所以没有将 nil 隐式转换为 String 是非常有意义的。

你应该改变

sg = SendGrid::API.new(api_key: ENV['xxxxxxx'])

为了:

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
于 2018-04-17T11:17:01.387 回答