Php email attachment extraction -
i'm trying create piece of code go mailbox , take out attachments of specific file. far able view if there attachment or if there not attachment on e-mail.
but want able take attachments out of e-mail , save them specified directory. type of attachment i'm trying take out .jpg
i've tried bunch of different pieces of code i've found on google , i've been trying tailor fit code, far have been unsuccessful in finding works correctly.
i wondering if able me create piece of code able take attachments out of emails , store them in directory.
thanks.
<?php /* connect email */ $hostname = '{*****.com:110/pop3}inbox'; $username = '*****'; $password = '*****'; // try connect $inbox = imap_open($hostname,$username,$password) or die('cannot connect server: ' . imap_last_error()); // grab emails $emails = imap_search($inbox,'all'); // search 39th email, has attachment $count = 39; // fetch information email $attachment = imap_fetchstructure($inbox, $count); // find out how may parts object has $numparts = count($attachment->parts); // find if if multipart message if ($numparts >= 2) { foreach ($attachment->parts $part) { if ($part->disposition == "inline") { // inline message. show number of lines printf("inline message has %s lines<br>", $part->lines); } elseif ($part->disposition == "attachment") { // attachment echo "attachment found!"; // print out file name echo "filename: ", $part->dparameters[0]->value; } } } //} else { // 1 part useful info echo "no attachment"; } imap_close($imap); ?>
instead of imap_search
used imap_check
retrieve messages overview, , following worked. go on messages found imap_check
, , how extract binary data of attachment:
$mbox = imap_open( . . . . ); $imapobj = imap_check($inbox); $start = $imapobj->nmsgs-30; $end = $imapobj->nmsgs; $result = imap_fetch_overview($inbox,"$start:$end",0); $count = $end; foreach ($result $overview) { $parts = mail_mime_to_array($inbox, $count); foreach($parts $part) { if(@$part['filename'] || @$part['name'] ) { $partname = $part['filename'] ? $part['filename'] : $part['name']; echo "attachment name " . basename($partname); echo "\n"; if(preg_match( . . . write here regex detect ".jpg" in $partname . . .)) { echo "found file! extracting binary data..."; $filecontents = $part['data']; file_put_contents("attachment.jpg", $filecontents); } } } }
Comments
Post a Comment