I'm using the Google App Engine (GAE) for PHP, and I'm trying to use the Mailgun API to send a message with an attachment using CURL.
The attachment is on Google Cloud Storage (because there are limitations on GAE for writing and reading files on a local filesystem). So what I'm doing is using a temporary file instead.
Here's my code so far:
$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);
For some reason, it doesn't work.
I've made sure the temp file is actually generated by putting it back into google cloud storage using this code:
$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);
When I run the above I'm simply taking the temporary file and uploading it back to Google Cloud Storage using a different name, and then I download it and open it to make sure it's the same as the original. No issues here.
Unfortunately, I can't seem to get CURL to work with it. When I comment out $post_data_arr['attachment'] = curl_file_create($tmp_path, 'application/pdf', 'proposal.pdf');
, the message is sent, albeit with no attachment.
How can I get this to work?