当通过PHP和CURL使用Mailgun时,什么'相当于PHPMailer'的AddStringAtta


What's the equivalent of the PHPMailer's AddStringAttachment when using Mailgun via PHP and CURL?

这是在使用Mailgun的类时问题的答案。我正在寻找一个适用于PHP内部使用CURL的答案。


使用PHPMailer的类,我可以以以下方式发送多个附件:

$mail->AddStringAttachment($attachment1, $title1);
$mail->AddStringAttachment($attachment2, $title2);

因为我没有从服务器获取文件,而是在一个字符串中组合,所以我需要为每个附件指定标题。


现在,我想通过PHP和CURL使用Mailgun来完成这个任务。到目前为止,我使用以下技术来发送没有附件的邮件:

$api_key="[my api key]";
$domain ="[my domain]";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'api:'.$api_key);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v2/'.$domain.'/messages');
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    "from" => "[sender]",
    "to" => $to,
    "subject" => $subject,
    "html" => $content
));

按照在数组中指定字段的相同约定,发送字符串附件并使用PHP和CURL与Mailgun指定标题的等效是什么?

我放弃了使用字符串附件,而是在一个临时目录(目录名基于用户的唯一ID)内创建了两个临时文件(基于先前由另一个函数组成的内容)。(感谢drew010引导我走上正确的道路。)

我怀疑下面的函数是否对其他人有用,但也许不同的部分将有助于其他需要类似功能的人。

function sendFormattedEmail ($coverNote, $attachment1, $title1, $attachment2, $title2) {
    global $userID, $account;
    if (!file_exists("temp_{$userID}")) {
        mkdir("temp_{$userID}");
    }
    file_put_contents("temp_{$userID}/{$title1}", $attachment1);
    file_put_contents("temp_{$userID}/{$title2}", $attachment2);
    $api_key="[api_key]";
    $domain ="[my_domain]";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, 'api:'.$api_key);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v2/'.$domain.'/messages');
    curl_setopt($ch, CURLOPT_POSTFIELDS, array(
        "from" => "[my_return_address]",
        "to" => $account,
        "subject" => "your requested files",
        "text" => $coverNote,
        "attachment[1]" => new CurlFile("temp_{$userID}/{$title1}"),
        "attachment[2]" => new CurlFile("temp_{$userID}/{$title2})"
    ));
    $response = curl_exec($ch);
    $response = strtolower(str_replace("'n", "", trim($response)));
    $result=  json_decode($response, true);
    $status = explode(".", $result["message"]);
    if ($status[0] == "queued") {
        echo json_encode(array ("result" => "success"));
    }
    else {
        echo json_encode(array ("result" => "failure"));
    }
    curl_close($ch);
    unlink ("temp_{$userID}/{$title1}");
    unlink ("temp_{$userID}/{$title2}");
    rmdir ("temp_{$userID}");
}

如上所示,该函数从Mailgun的响应中去掉换行字符,以便启用json_encode。修剪和小写转换只是我的偏好。

将结果报告给调用函数后,它删除两个临时文件,然后删除临时目录。