[英]How to send dynamic template mail via guzzle HTTP in PHP
我正在嘗試使用 PHP 中的 Guzzle HTTP 通過 SendGrid 中的動態模板發送 email。
但我無法發送郵件。 因為我只得到如下錯誤而沒有任何理由。
Type: GuzzleHttp\Exception\ClientException
Message: Client error: `POST https://api.sendgrid.com/v3/mail/send` resulted in a `400 Bad Request` response: {"errors":[{"message":"Bad Request","field":null,"help":null}]}
我的 PHP 示例代碼:
require __DIR__.'../../vendor/autoload.php';
$CLIENT = new GuzzleHttp\Client();
$response = $CLIENT->request('POST', 'https://api.sendgrid.com/v3/mail/send', [
"headers" => [
"Authorization" => "Bearer my-api-key",
"Content-Type" => "application/json"
],
'data' => '{
"from": {
"email": "admin@example.com"
},
"personalizations": [{
"to": [{
"email": "me@gmail.com"
}],
"dynamic_template_data": {
"email_data": [{
"id": "2",
"title": "Artificial Intelligence in Health Care",
"image": "https://example.com//uploads/3663581583995181_0724.jpg",
"description": "Immediate application of AI in the Health Care domains."
}, {
"id": "199",
"title": "Aesthetics Skill Discussion 3 by Jranand",
"image": "",
"description": "Aesthetics Skill Discussion 3 by Jranand"
}]
}
}],
"template_id": "my-template-id"
}',
]);
echo $response->getStatusCode();
我能夠通過 SendGrid 中的動態模板測試方法使用相同的 dynamic_template_data 發送 email。 但是用 Guzzle HTTP 試試這個。 我無法找到錯誤的原因。
能夠在測試中發送帶有動態 JSON 數據的 email。
誰能幫我解決這個問題?
提前致謝。
json 中沒有數據請求選項,您需要更改代碼,您可以使用guzzle的 json 請求選項(需要較少的努力),或者您可以直接糾正您的身體。
try{
$CLIENT = new GuzzleHttp\Client();
$data = [
"from" => [
"email" => "admin@example.com"
],
"personalizations" => [
[
"to" => [
[
"email" => "me@gmail.com"
]
],
"dynamic_template_data" => [
"email_data" => [
[
"id" => "2",
"title" => "Artificial Intelligence in Health Care",
"image" => "https://example.com//uploads/3663581583995181_0724.jpg",
"description"=> "Immediate application of AI in the Health Care domains."
],
[
"id" => "199",
"title" => "Aesthetics Skill Discussion 3 by Jranand",
"image" => "",
"description" => "Aesthetics Skill Discussion 3 by Jranand"
]
]
]
]
],
"template_id" => "my-template-id"
];
$response = $CLIENT->request('POST', 'https://api.sendgrid.com/v3/mail/send', [
"headers" => [
"Authorization" => "Bearer my-api-key",
"Content-Type" => "application/json"
],
'json' => $data,
]);
if ($guzzleResponse->getStatusCode() == 200) {
$response = json_decode($guzzleResponse->getBody(),true);
//perform your action with $response
}
}
catch(\GuzzleHttp\Exception\RequestException $e){
// you can catch here 400 response errors and 500 response errors and log those errors
}catch(Exception $e){
//other errors
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.