I’m following the example here: https://github.com/sendgrid/sendgrid-php/blob/master/examples/mail/mail.php
I’ve stripped the majority of parameters to send a very basic email:
<?php
require 'vendor/autoload.php'; // If you're using Composer (recommended)
$apiKey = getenv('SENDGRID_API_KEY');
$sg = new SendGrid($apiKey);
$request_body = json_decode('{
"content": [
{
"type": "text/html",
"value": "<html><p>Hello, world!</p></html>"
}
],
"from": {
"email": "alice@domain.com",
"name": "Sender Alice"
},
"personalizations": [
{
"to": [
{
"email": "bob@domain.com",
"name": "Receiver Bob"
}
]
}
],
}');
try {
$response = $sg->client->mail()->send()->post($request_body);
print $response->statusCode() . "n";
print_r($response->headers());
print $response->body() . "n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "n";
}
?>
When executed I get the following error
{"errors":[{"message":"Content-Type should be application/json.","field":null,"help":null}]}
Looking at the original example, I don’t see anything that I might have removed that would cause this, although I’m probably wrong.
Thanks for any input.
Advertisement
Answer
Try removing the last , in your request_body variable.
Change
"personalizations": [
{
"to": [
{
"email": "bob@domain.com",
"name": "Receiver Bob"
}
]
}],
To this
"personalizations": [
{
"to": [
{
"email": "bob@domain.com",
"name": "Receiver Bob"
}
]
}]
When I run into these problems I run my json against a validator. A lot of times it’ll give me an idea of where to start.