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

时间:2018-05-22 13:28:40

标签: php json email sendgrid sendgrid-api-v3

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

2 个答案:

答案 0 :(得分: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);

希望这会对你有所帮助。

答案 1 :(得分:1)

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

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

输出与您的要求相同。