我正在使用Google App Engine(GAE)for PHP,並且我試圖使用Mailgun API來發送帶有使用CURL附件的郵件。使用PHP Curl和Mailgun API使用遠程文件發送帶附件的郵件
該附件位於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 <[email protected]>',
'to' => '[email protected]',
'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);
當我跑我只是採取臨時文件並上傳上述回到谷歌雲存儲使用不同的名稱,然後我下載並打開它,以確保它與原始相同。這裏沒有問題。
不幸的是,我似乎無法讓CURL使用它。當我註釋掉$post_data_arr['attachment'] = curl_file_create($tmp_path, 'application/pdf', 'proposal.pdf');
時,會發送該消息,儘管沒有附件。
我該如何得到這個工作?
這可能會有所幫助:http://stackoverflow.com/questions/14229656/mailgun-sent-mail-with-attachment – Rainner
謝謝。我之前嘗試過使用'@'方法,但由於我無法動態創建本地文件,因此它將無法工作,因爲沒有帶文件擴展名的文件,只有一個句柄。此外,該方法已被棄用。 –