ruby-on-railsrubysendgridsendgrid-templates

Send transactional email with SendGrid on a Rails app


I am trying to send a transactional email using Sendgrid upon client booking on a Rails application.

I did create a dynamic template as required. When I make a POST request to https://api.sendgrid.com/v3/mail/send with POSTMAN using the right body and my Sendgrid API key, it works, I do receive the confirmation email.

However, I am a Rails newbie and I really don't know how to proceed with the piece of code provided in the docs:

require 'sendgrid-ruby'
include SendGrid

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'], impersonate_subuser: The subuser's username. This header generates the API call as if the subuser account was making the call.)
data = JSON.parse('{
  "name": "example_name",
  "generation": "dynamic"
}')

response = sg.client.templates.post(request_body: data)
puts response.status_code
puts response.headers
puts response.body

Thanks in advance for your help!


Solution

  • Twilio SendGrid developer evangelist here.

    Check out the documentation here that shows all the options you can use to send an email with the Ruby library (excuse the use of include).

    Based on the docs, here's a quick snippet that should cover your needs:

    require 'sendgrid-ruby'
    
    sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
    mail = SendGrid::Mail.new
    
    mail.from = SendGrid::Email.new(email: "YOUR_FROM_ADDRESS")
    mail.subject = "Your fancy, exciting subject line"
    mail.template_id = "YOUR_TEMPLATE_ID"
    
    personalization = SendGrid::Personalization.new
    personalization.add_to(SendGridEmail.new(email: 'YOUR_CUSTOMER_EMAIL'))
    personalization.add_dynamic_template_data({
      "name" => "example_name",
      "generation" => "dynamic"
    })
    mail.add_personalization(personalization)
    
    sg.client.mail._("send").post(request_body: mail.to_json)
    

    Take a look at this specific example in the SendGrid Ruby library docs too.