I'm currently trying to send emails via the Sendgrid SMTP API. I have a "name" substitution which replaces tags in the email with recipient's names. However, I'm running into an issue where my SMTP JSON gets declined as invalid by Sendgrid.
The issue is because the names have spaces, and the Swift mailer wraps the lines here. The linebreaks end up being in the middle of names, making those strings invalid JSON leading to Sendgrid turning that email down. I'm generating the header using Sendgrid's own SMTP API PHP library but this does not do the linewrapping for you.
I'm trying to find a way to wrap my JSON in a way that doesn't make it invalid. I haven't been able to find any PHP solutions. Sendgrid themselves give a PERL regex example, which I unsuccessfully attempted to do in PHP.
I also found a Ruby solution that is promising, but my application server supports ONLY PHP. This is the Ruby solution I found.
This is the code I'm using to send the emails.
<?php
//...
$header = new Header(); // This is the sendgrid API header class
$header->setTos(array_column($subscribers, 'email'));
$header->addSubstitution('-SubscriberName-', array_column($subscribers, 'name'));
$header->addSubstitution('-SubscriberId-', array_column($subscribers, 'id'));
// $message is a SwiftMessage
$message->getHeaders()->addTextHeader(strtoupper(Header::NAME), $header->jsonString());
This is how the header value is set, according to logs. I've removed personal data but you can see how "The(\n)Shop" would cause the aforementioned invalid JSON error. This happens many times through out the name substitutions.
X-SMTPAPI: {"to":[/* emails removed, but there were no spaces so all emails were on one very long line */],"sub":{"-SubscriberName-":["Joseph","Alexandra","Michelle","Nicky","Des","Clive","Peter","Robert","Tedy","Terry","Terry","Terry","Tessa","The
Shop","Thomas","Tim","Tim","Tina","Tina","Tobias","Tom","Tommy", //...