0

我正在尝试使用 v3 API 通过 Sendgrid 发送电子邮件,我想传递与此类似的 json 数据

{ 
"personalizations": [
    {
      "to": [
        {
          "email": "john.doe@example.com",
          "name": "John Doe"
        }
      ],
      "subject": "Hello, World!"
    }
  ],
  "from": {
    "email": "sam.smith@example.com",
    "name": "Sam Smith"
  },
  "reply_to": {
    "email": "sam.smith@example.com",
    "name": "Sam Smith"
  }
}

我的代码:

$email_content = [
                'personalizations' => [
                    'to' => [
                        'email' => 'ashuomble5@gmail.com',
                        'name' => 'Ashutosh'
                    ],
                    'subject' => 'Test'
                ],
                'from' => [
                    'email' => 'ashuomble5@gmail.com',
                    'name' => 'Ashu'
                ],
                'reply_to' => [
                    'email' => 'ashuomble5@gmail.com',
                    'name' => 'AO'
                ],
                'content' => [
                    'type' => 'text/plain',
                    'value' => 'Hello'
                ]
            ];

json_encode() 输出后格式如下:

{
   "personalizations":{
      "to":{
         "email":"ashuomble5@gmail.com",
         "name":"Ashutosh"
      },
      "subject":"Test"
   },
   "from":{
      "email":"ashuomble5@gmail.com",
      "name":"Ashu"
   },
   "reply_to":{
      "email":"ashuomble5@gmail.com",
      "name":"AO"
   },
   "content":{
      "type":"text\/plain",
      "value":"Hello"
   }
}

任何帮助将不胜感激。出于特定原因,我只想使用 v3 API

4

2 回答 2

2

查看您的 json 结构,它看起来确实与他们在文档中的显示方式不同,请注意“个性化”和“到”是对象。https://sendgrid.com/docs/API_Reference/api_v3.html,他们还在发送前对数据进行字符串化。

var data = JSON.stringify({
  "personalizations": [
    {
      "to": [
        {
          "email": "john.doe@example.com",
          "name": "John Doe"
        }
      ],
      "subject": "Hello, World!"
    }
  ],
  "from": {
    "email": "sam.smith@example.com",
    "name": "Sam Smith"
  },
  "reply_to": {
    "email": "sam.smith@example.com",
    "name": "Sam Smith"
  }
});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://api.sendgrid.com/v3/mail/send");
xhr.setRequestHeader("authorization", "Bearer <<YOUR_API_KEY>>");
xhr.setRequestHeader("content-type", "application/json");

xhr.send(data);

希望这对您有所帮助。

于 2018-05-22T13:45:33.350 回答
1

您需要将 [] - 括号添加到您的“到”数组中。请看一看。

'to' => [
    [ // add this brackets
        'email' => 'ashuomble5@gmail.com',
        'name' => 'Ashutosh'
    ] // add this brackets 
],

输出将与您的要求相同。

于 2018-05-22T13:42:52.020 回答