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

我在这里遵循示例: 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}]}


看看原来的例子,我没有看到任何我可能删除的东西会导致这种情况,尽管我可能是错的。


感谢您的任何意见。


阿波罗的战车
浏览 97回答 1
1回答

茅侃侃

,尝试删除request_body 变量中的最后一个。改变"personalizations": [{&nbsp; "to": [&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "email": "bob@domain.com",&nbsp;&nbsp; &nbsp; &nbsp; "name": "Receiver Bob"&nbsp; &nbsp; }&nbsp; ]}],&nbsp;对此"personalizations": [{&nbsp; "to": [&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "email": "bob@domain.com",&nbsp;&nbsp; &nbsp; &nbsp; "name": "Receiver Bob"&nbsp; &nbsp; }&nbsp; ]}]当我遇到这些问题时,我会针对验证器运行 json。很多时候它会让我知道从哪里开始。https://jsonlint.com/
打开App,查看更多内容
随时随地看视频慕课网APP