Mandrill ValidationError

Dan*_*Dan 11 php json mandrill

非常高兴能在StackOverflow上提出我的第一个问题.这些年来,我一直依靠它来教自己很多!

我的问题是这个.尝试通过Mandrill的API发送邮件时出现以下错误:

{"status":"error","code":-1,"name":"ValidationError","message":"You must specify a key value"}
Run Code Online (Sandbox Code Playgroud)

下面的代码是我用来尝试发送邮件的代码:

<?php
$to = 'their@email.com';
$content = '<p>this is the emails html <a href="www.google.co.uk">content</a></p>';
$subject = 'this is the subject';
$from = 'my@email.com';

$uri = 'https://mandrillapp.com/api/1.0/messages/send.json';
$content_text = strip_tags($content);

$postString = '{
"key": "RR_3yTMxxxxxxxx_Pa7gQ",
"message": { 
 "html": "' . $content . '",
 "text": "' . $content_text . '",
 "subject": "' . $subject . '",
 "from_email": "' . $from . '",
 "from_name": "' . $from . '",
 "to": [
 {
 "email": "' . $to . '",
 "name": "' . $to . '"
 }
 ],
 "track_opens": true,
 "track_clicks": true,
 "auto_text": true,
 "url_strip_qs": true,
 "preserve_recipients": true
},
"async": false
}';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
$result = curl_exec($ch);
echo $result;

?>
Run Code Online (Sandbox Code Playgroud)

什么可能导致消息中的验证错误.我提供我的API密钥,它是有效的!

希望有人能够提供帮助,并且感谢您在这里一般都很棒!

谢谢!

Kai*_*lin 12

您可能还想使用数组,让PHP为您处理JSON编码.如果JSON由于某种原因无效,则此特定错误很常见.因此,例如,您可以像这样设置参数:

$params = array(
    "key" => "keyhere",
    "message" => array(
        "html" => $content,
        "text" => $content_text,
        "to" => array(
            array("name" => $to, "email" => $to)
        ),
        "from_email" => $from,
        "from_name" => $from,
        "subject" => $subject,
        "track_opens" => true,
        "track_clicks" => true
    ),
    "async" => false
);

$postString = json_encode($params);
Run Code Online (Sandbox Code Playgroud)

json_decode如果需要,您还可以使用解析响应.


小智 12

Bansi的答案适用于Dan B,但如果其他人遇到同样的问题,那么检查内容是否有特殊字符(重音符号,变音符号,cedillas,撇号等)是很好的.如果是这种情况,解决方案可能是utf8编码文本:

$content = utf8_encode('<p>Greetings from Bogotá, Colombia. Att:François</p>');
Run Code Online (Sandbox Code Playgroud)