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

时间:2020-07-22 21:35:50

标签: php sendgrid

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

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

感谢您的任何输入。

1 个答案:

答案 0 :(得分:1)

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

更改

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

对此

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

遇到这些问题时,我将对验证器运行json。很多时候,它会让我对从哪里开始有所了解。

https://jsonlint.com/