我正在尝试测试Sendgrid的交易模板以便工作。当值被硬编码时,我能够发送邮件,但是当我为它们提供变量时却没有。让我们来看看:
我的标题:
$headers = array(
'Content-Type: application/json',
'Authorization: Bearer my_actual_api_key',
);
我的$ data数组:
$resetLink = 'na';
$reset = 'Please, click here to activate your account';
$user = 'MyName';
$data = ['reset'=>$reset, 'user'=>$user, 'resetLink'=>$resetLink];
$ subs是通过执行以下操作创建的:
if($data){
foreach($data as $k=>$v){
$subs.= '"{{'.$k.'}}":"'.$v.'"';
if($last_element != $v){
$subs .=",";
}
}
}
输出:
"{{reset}}": "Please, click here to activate your account.",
"{{user}}": "MyName",
"{{resetLink}}": "na"
正是我想要的!
然而,如果我这样做:
$json = '{
"personalizations": [{
"to": [{
"email": "'.$to.'",
"name": "Example 01"
}],
"subject": "'.$subject.'",
"substitutions": {
'.$subs.'
}
}],
"from": {
"email": "'.$from.'",
"name": "'.$from.'"
},
"reply_to": {
"email": "'.$from.'",
"name": "'.$from.'"
},
"template_id": "My_actual_temnplate_id"
}';
我回来了:
{"errors":[{"message":"Bad Request","field":null,"help":null}]}
但是,如果我这样做:
$json = '{
"personalizations": [{
"to": [{
"email": "'.$to.'",
"name": "Example 01"
}],
"subject": "'.$subject.'",
"substitutions": {
"{{reset}}": "Please, click here to activate your account.",
"{{user}}": "MyName",
"{{resetLink}}": "na"
}
}],
"from": {
"email": "'.$from.'",
"name": "'.$from.'"
},
"reply_to": {
"email": "'.$from.'",
"name": "'.$from.'"
},
"template_id": "1959ba19-3bc7-455b-a577-7a340f4c5fd9"
}';
我可以使用以下内容轻松发送并发送邮件。
继承人cURL,标准的东西:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.sendgrid.com/v3/mail/send");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
我也尝试将这个json作为一个数组,然后使用json_encode(),也没有运气,同样的错误非消息,如上所述。这是在Sendgrid网站上提供的json,只是fyi。
正如您所看到的,我将所有内容都视为字符串,这可以解释我找到的大多数答案。有人可以解释为什么会这样吗?提前谢谢!
答案 0 :(得分:0)
今天早上来了,代码工作了,生成替换的循环没有进一步的问题。框架(Yii2)是缓存。只需几个小时就可以刷新1次。