Add category to send grid mail using web api

2.5k views Asked by At

I'm Tracking my send grid mail activities. I want to add category to my mail headers. This is the code I used:

$params = array(
    'api_user'  => 'xxx',
    'api_key'   => 'xxxx',
    'to'        => $to,
    'subject'   => $subject,
    'html'      => $message,
    'from'      => $from,
    'category'  => 'news',   
);

$request =  $url.'api/mail.send.json';
$session = curl_init($request);
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($session);
curl_close($session);

But the category (news) is not added in the send grid statistics. How can add category to mail.

1

There are 1 answers

1
Martyn Davies On BEST ANSWER

You need to pass categories as JSON to the x-smtpapi param rather than incuding it at the top level. Like so:

$categories = array("category" => "news");
$params = array(
  'api_user'  => 'xxx',
  'api_key'   => 'xxxx',
  'to'        => $to,
  'subject'   => $subject,
  'html'      => $message,
  'from'      => $from,
  'x-smtpapi'  => json_encode($categories)   
);

You can see another example of this in practice in the SendGrid Documentation. Additionally, here are the docs for all the things you can do with the X-SMTPAPI headers, and we also have a validator for those headers as well.