sendgrid / sendgrid-ruby

The Official Twilio SendGrid Led, Community Driven Ruby API Library
https://sendgrid.com
MIT License
624 stars 323 forks source link

How to quote name with special characters #394

Closed NeoPhi closed 4 years ago

NeoPhi commented 5 years ago

Issue Summary

SendGrid support directed me here since they were able to confirm but unable to solve an issue we are seeing. Given the following code:

    mail = SendGrid::Mail.new()
    personalization = SendGrid::Personalization.new()
    personalization.add_to(SendGrid::Email.new(email: "test@example.com", name: "Howdy y'all :("))
    mail.add_personalization(personalization)
    mail_json = mail.to_json()

This generates:

{"personalizations"=>[{"to"=>[{"email"=>"test@example.com", "name"=>"Howdy y'all :("}]}]}

The API is unable to handle this name and the email is not sent to the intended user. SendGrid support indicates that a name that includes any of (),:;<>@[] is problematic. This is a much more extensive list then documented at: https://sendgrid.api-docs.io/v3.0/mail-send/mail-send-limitations

To resolve the issue they said the JSON payload needed to be:

{"personalizations"=>[{"to"=>[{"email"=>"test@example.com", "name"=>"\"Howdy y'all :(\""}]}]}

Notice the inclusion of the escaped double quotes \" in the name. However support was unable to indicate how to properly modify the code snippet above to ensure that names with special characters are handled correctly. Is it just a case of always wrapping the name in double quotes " before setting it? Would special handling be required if the name already included a double quote in it?

Technical details:

childish-sambino commented 4 years ago

Yes, wrapping the name string in double-quotes is all that's needed. If the name already contains double-quotes that should be okay as they will get escaped as well. Example:

name = "Howdy y'all :("
personalization.add_to(SendGrid::Email.new(email: "test@example.com", name: '"' + name + '"'))

Checking to see if/when this can be fixed on the backend, but no timetable yet. Also note that this doesn't affect all traffic/customers, but the above fix should work.