使用PHP Curl和Mailgun API使用远程文件发送带附件的邮件

时间:2016-01-23 15:32:29

标签: php google-app-engine curl mailgun

我正在使用Google App Engine(GAE)进行PHP,并且我尝试使用Mailgun API使用CURL发送带附件的邮件。

附件位于Google云端存储上(因为GAE在本地文件系统上写入和读取文件时存在限制)。所以我正在做的是使用临时文件。

到目前为止,这是我的代码:

$url_str = 'https://api.mailgun.net/v3/es.restive.io/messages';
$auth_user_str = 'api';
$auth_pass_str = 'key-my-unique-key';
$post_data_arr = array(
    'from' => 'Sender <info@email.com>',
    'to' => 'recipient@email.com',
    'subject' => 'Test Mail from GAE',
    'html' => '<html><body><strong><p>a simple HTML message from GAE</p></strong></body></html>',
    'o:tracking' => 'yes'
);
$headers_arr = array("Content-Type:multipart/form-data");
$file_gs_str = 'gs://my_bucket/attachment.pdf';

$tmp_path = tempnam(sys_get_temp_dir(), '');
$handle = fopen($tmp_path, "w");
fwrite($handle, file_get_contents($file_gs_str));
fseek($handle, 0);

$post_data_arr['attachment'] = curl_file_create($tmp_path, 'application/pdf', 'proposal.pdf');

$cl = curl_init();
curl_setopt($cl, CURLOPT_URL, $url_str);
curl_setopt($cl, CURLOPT_TIMEOUT, 30);
curl_setopt($cl, CURLOPT_HTTPHEADER, $headers_arr);
curl_setopt($cl, CURLOPT_POST, true);
curl_setopt($cl, CURLOPT_POSTFIELDS, $post_data_arr);
curl_setopt($cl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cl, CURLOPT_USERPWD, "$auth_user_str:$auth_pass_str");

$status_code = curl_getinfo($cl);
$response = curl_exec($cl);

fclose($handle);
curl_close($cl);

出于某种原因,它不起作用。

我确保使用此代码将临时文件放回谷歌云存储中来生成临时文件:

$options = ['gs' => ['Content-Type' => 'application/pdf']];
$ctx = stream_context_create($options);
file_put_contents('gs://my_bucket/re_attachment.pdf', file_get_contents($tmp_path), 0, $ctx);

当我运行上述操作时,我只需将临时文件上传并使用其他名称将其上传回Google云端存储,然后下载并打开它以确保它与原本的。这里没有问题。

不幸的是,我似乎无法让CURL使用它。当我注释掉$post_data_arr['attachment'] = curl_file_create($tmp_path, 'application/pdf', 'proposal.pdf');时,会发送消息,尽管没有附件。

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:1)

首先,确保运行PHP 5.5,因为只有PHP 5.5支持curl_file_create()。

然后,尝试明确地删除设置标头。当CURLOPT_POSTFIELDS的值是一个数组时,Curl会自动为multipart / form-data设置一个标头。所以,摆脱这个:

curl_setopt($cl, CURLOPT_HTTPHEADER, $headers_arr);