【问题标题】:Using PHP Curl and Mailgun API to send mail with attachment using remote file使用 PHP Curl 和 Mailgun API 使用远程文件发送带有附件的邮件
【发布时间】: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'); 时,消息已发送,尽管没有附件。

我怎样才能让它工作?

【问题讨论】:

  • 这可能会有所帮助:stackoverflow.com/questions/14229656/…
  • 谢谢。我之前尝试过使用@ 方法,但是由于我无法动态创建本地文件,因此它不起作用,因为没有文件扩展名的文件,只有一个句柄。此外,该方法已被弃用。

标签: php google-app-engine curl mailgun


【解决方案1】:

首先,确保您运行的是 PHP 5.5,因为 curl_file_create() 仅受 PHP 5.5 支持。

然后,尝试摆脱显式设置标题。当 CURLOPT_POSTFIELDS 的值为数组时,Curl 会自动为 multipart/form-data 设置一个 header。所以,摆脱这个:

curl_setopt($cl, CURLOPT_HTTPHEADER, $headers_arr);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2021-10-10
    • 2012-12-23
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多