邮件发送错误由phpg中的mailgun API

时间:2016-10-25 09:43:10

标签: mailgun

我正在尝试使用mailgum API发送邮件。 由于它是共享服务器,我无法安装composer(加载mailgun SDK)。相反,我正在使用卷曲。 这是我的代码:     

function send_simple_message() {  
$api_key = "key-9dc0bf ... 2e4c1007d0ebd7c8";
$domain=     "https://api.mailgun.net/v3/sandbox.mailgun.org";

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
 curl_setopt($ch, CURLOPT_USERPWD, $api_key);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
 curl_setopt($ch, CURLOPT_URL, $domain);
 curl_setopt($ch, CURLOPT_POSTFIELDS, 
            array('from' => 'Ruhul Amin <testemail@gmail.com>',
                  'to' => 'Michael Scott <test2@gmail.com>',
                  'subject' => 'The Printer Caught Fire',
                  'text' => 'We have a problem.'));
 $result = curl_exec($ch);
 curl_close($ch);
 return $result;
}

var_dump ( send_simple_message() );

?>

输出是:      布尔(假)

但不发送电子邮件。 你能告诉我我的问题是什么吗? 感谢。

Ruhul

3 个答案:

答案 0 :(得分:1)

我解决了这个问题。我在这里发帖,希望它会帮助一些人。 实际上,CURLOPT_USERPWD - 用于身份验证的用户名和密码 所以,在我的例子中,用户名是:api,用户密码是API密钥 我需要在定义$ api-key

时合并它
function send_simple_message() {  
$api_key = "api:key-9dc0bf ... 2e4c1007d0ebd7c8";
$domain=     "https://api.mailgun.net/v3/sandbox.mailgun.org";

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
 curl_setopt($ch, CURLOPT_USERPWD, $api_key);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
 curl_setopt($ch, CURLOPT_URL, $domain);
 curl_setopt($ch, CURLOPT_POSTFIELDS, 
        array('from' => 'Ruhul Amin <testemail@gmail.com>',
              'to' => 'Michael Scott <test2@gmail.com>',
              'subject' => 'The Printer Caught Fire',
              'text' => 'We have a problem.'));
 $result = curl_exec($ch);
 curl_close($ch);
 return $result;
}

var_dump ( send_simple_message() );

答案 1 :(得分:0)

如果curl_exec返回false,则表示存在错误。您可以使用curl_error函数获取错误消息。查看curl_error函数的输出,您将更接近它的工作。示例代码:

$result = curl_exec($ch);
if ($result === false)
{
    $error = curl_error($ch);
    // do something with the error
}

答案 2 :(得分:0)

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $mailgun_api_url,
    CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
    CURLOPT_USERPWD => "api:{$mailgun_api_key}",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_SSL_VERIFYPEER => 0,
    CURLOPT_SSL_VERIFYHOST => 0,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => [
        "from" => "emailfrom@app.com",
        "to" => "emailto@app.com",
        "subject" => "subject of mail",
        "text" => "description/content of the mail."
    ]
]);
$res = curl_exec($ch);
curl_close($ch);

确保$ mailgun_api_url和$ mailgun_api_key应该是正确的并检查$ res它应该是json,如下所示

{
    "id": "<messageid@domain.com>",
    "message": "Queued. Thank you."
}

如果接收电子邮件ID正确,则会发送消息。