使用 v3 API 通过 sendgrid 发送电子邮件

Send Email via sendgrid using v3 API

我正在尝试使用 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

您需要在 'to' 数组中添加 [] - 方括号。请看一下。

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

输出将与您的要求相同。

查看您的 json 结构,它看起来确实与他们在文档中显示的方式不同,请注意 "personalizations" 和 "to" 是对象。 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);

希望对您有所帮助。