Last active
March 27, 2019 01:40
-
-
Save peacefixation/78231aaeaafbb10e4ef65a584d784c62 to your computer and use it in GitHub Desktop.
Save email attachment with mailparse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/php | |
| <?php | |
| // create a resource | |
| $parsed = mailparse_msg_create(); | |
| // read the mime-encoded email file from stdin | |
| $email = file_get_contents('php://stdin'); | |
| // parse the mime-encoded email | |
| mailparse_msg_parse($parsed, $email); | |
| $structure = mailparse_msg_get_structure($parsed); | |
| foreach($structure as $s) { | |
| $part = mailparse_msg_get_part($parsed, $s); | |
| $part_data = mailparse_msg_get_part_data($part); | |
| $headers = $part_data['headers']; | |
| if(array_key_exists('content-disposition', $part_data) && $part_data['content-disposition'] == 'attachment') { | |
| $file_data_encoded = substr($email, $part_data['starting-pos-body'], $part_data['ending-pos-body']); | |
| $file_data = base64_decode($file_data_encoded); | |
| $filename = $part_data['disposition-filename']; | |
| $file = fopen('/tmp/' . $filename, "w+"); | |
| fwrite($file, $file_data); | |
| fclose($file); | |
| } | |
| } | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment