【发布时间】:2016-04-30 03:38:24
【问题描述】:
我正在使用适用于 PHP 的 Google App Engine (GAE),并且正在尝试使用 Mailgun API 通过 CURL 发送带有附件的消息。
附件位于 Google Cloud Storage 上(因为 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 Cloud Storage,然后我下载并打开它以确保它与原始文件相同。这里没有问题。
不幸的是,我似乎无法让 CURL 使用它。当我注释掉$post_data_arr['attachment'] = curl_file_create($tmp_path, 'application/pdf', 'proposal.pdf'); 时,消息已发送,尽管没有附件。
我怎样才能让它工作?
【问题讨论】:
-
谢谢。我之前尝试过使用
@方法,但是由于我无法动态创建本地文件,因此它不起作用,因为没有文件扩展名的文件,只有一个句柄。此外,该方法已被弃用。
标签: php google-app-engine curl mailgun