Get attachment from Mailgun Form Post PHP

How to receive and save an attachment sent to me via a form message with Mailgun POST

Below are some options

attachment-1 {:filename=>"crabby.gif", :type=>"image/gif", :name=>"attachment-1", :tempfile=>#<Tempfile:/tmp/RackMultipart20140707-2-slsrkh>, :head=>"Content-Disposition: form-data; name=\"attachment-1\"; filename=\"crabby.gif\"\r\nContent-Type: image/gif\r\nContent-Length: 2785\r\n"} attachment-2 {:filename=>"attached_.txt", :type=>"text/plain", :name=>"attachment-2", :tempfile=>#<Tempfile:/tmp/RackMultipart20140707-2-sudxuf>, :head=>"Content-Disposition: form-data; name=\"attachment-2\"; filename=\"attached_.txt\"\r\nContent-Type: text/plain\r\nContent-Length: 32\r\n"} Content-Type multipart/mixed; boundary="------------020601070403020003080006" 
+6
source share
2 answers

So, I know that this is for a year, but I had the same problem, and I figured out how to load attachments. Files in the message are stored in the environment variable $ _ FILES . The information for each file will look something like this:

 Array ( [attachment-1] => Array ( [name] => ATextFile.txt [type] => text/plain [tmp_name] => /tmp/php8zhmlU [error] => 0 [size] => 70144 ) ) 

The file path is stored in tmp_name , so in this case /tmp/php8zhmlU is the full path to the file. move_uploaded_file will overwrite any existing files! To download all attachments from POST , I wrote a function:

 function download_attachments($pathToDownloadDirectory) { foreach($_FILES as $file) { if($file['error'] == "0") { if(!(move_uploaded_file($file['tmp_name'], $pathToDownloadDirectory . $file['name']))) { return 0; } } else { return 0; } } return 1; } download_attachments("/Full/Path/To/Some/Dir/"); 

The documentation for this top can be found here.

+6
source
  • Use the vault action from a route session to retrieve information about your email. ( retrieving a saved message
  • json_decode attachment property to get information about your attachments
  • get the api key and use the php library to use get api.

If you are json decoded attachment list - this is $ files, you can do

 $mgClient = new Mailgun('yourApiKey'); foreach ($files as $file){ file_put_contents($file->name,$mgClient->get($file->url)->http_response_body); } 

to download all attachments

+4
source

Source: https://habr.com/ru/post/971850/


All Articles