I'm fairly new to Ruby on Rails and SendGrid.
I cannot figure out why the code sample below does not work? It does send an email using the correct template, but the dynamic data does not fill in. Any input/insight is appreciated.
require 'sendgrid-ruby'
include SendGrid
mail = SendGrid::Mail.new
mail.template_id = 'template id'
mail.from = Email.new(
email: '[email protected]',
name: 'ABC')
personalization = SendGrid::Personalization.new
personalization.add_to(Email.new(email: '[email protected]', name: 'ABC'))
personalization.add_dynamic_template_data(
'variable' => [
{ 'first_name' => 'John' },
{ 'last_name' => 'Doe' },
{ 'email' => '[email protected]' },
{ 'message' => 'The message is as follows' }
]
)
mail.add_personalization(personalization)
sgp = SendGrid::API.new(api_key: ENV['sendgrid_api_key'])
response = sgp.client.mail._('send').post(request_body: mail.to_json)
The template code looks like the following.
Hello from {{first_name}} {{last_name}}.
{{message}}
And the result ends up without the variable values filled in.
Hello from .
CodePudding user response:
Twilio SendGrid developer evangelist here.
The dynamic data that you are adding is more complicated than the template. Instead of sending an array of hashes as the dynamic data, you can just send a hash. Try this instead:
personalization.add_dynamic_template_data({
'first_name' => 'John',
'last_name' => 'Doe',
'email' => '[email protected]',
'message' => 'The message is as follows'
})