由于 JSON 中的错误,使用 sendgrid PHP 发送邮件失败

Sending mail with PHP using sendgrid fails due to mistake in JSON

我按照这里的例子: https://github.com/sendgrid/sendgrid-php/blob/master/examples/mail/mail.php

我删除了大部分参数以发送一封非常基本的电子邮件:

<?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";
}
?>

执行时出现以下错误

{"errors":[{"message":"Content-Type should be application/json.","field":null,"help":null}]}

查看原始示例,虽然我可能错了,但我没有看到我可能删除的任何内容会导致此问题。

感谢任何意见。

尝试删除 request_body 变量中的最后一个 ,

改变

"personalizations": [
{
  "to": [
    {
      "email": "bob@domain.com", 
      "name": "Receiver Bob"
    }
  ]
}], 

对此

"personalizations": [
{
  "to": [
    {
      "email": "bob@domain.com", 
      "name": "Receiver Bob"
    }
  ]
}]

当我 运行 遇到这些问题时,我 运行 我 json 反对验证者。很多时候它会让我知道从哪里开始。

https://jsonlint.com/