ruby-on-railsrubyemailsendgridsendgrid-rails

Sendgrid implementation - no implicit conversion of nil into String


I've set my environment like so:

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

Sendgrid gem is installed.

Code I try to run:

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

But I get the following error:

no implicit conversion of nil into String

Inside this file:

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

I cant figure out what goes wrong here....

Full error:

/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>'

Solution

  • You are confusing the value of the env variable (xxxxxxxxx) with it's name (SENDGRID_API_KEY).

    When setting the API key in your code, use

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

    instead.