Hi guys! Hopefully somebody can help me with this. I found this code on a google search for extracting attachments from emails.
[code=php]<?php
$server = “{imap.gmail.com:993/imap/ssl}INBOX”;
$username = "[email protected]";
$password = “password”;
$mbox = imap_open($server, $username, $password);
// Getting all emails
if ($headers = imap_headers($mbox)) {
$i = 0;
foreach ($headers as $val) {
$i ++;
$info = imap_headerinfo($mbox, $i);
// Gets the current email structure (including parts)
// Use var_dump($structure) to check it out
$structure = imap_fetchstructure($mbox, $info->Msgno);
$attachments = get_attachments($structure);
foreach ($attachments as $k => $at) {
$content = imap_fetchbody($mbox, $info->Msgno, $at[‘part’]);
switch ($at[‘encoding’]) {
case ‘3’:
$content = base64_decode($content);
break;
case ‘4’:
$content = quoted_printable_decode($content);
break;
}
}
}
}
// Shutting down
imap_close($mbox);
/**
- Gets all attachments
- Including inline images or such
- @author: Axel de Vignon
- @param $content: the email structure
- @param $part: not to be set, used for recursivity
- @return array(type, encoding, part, filename)
*/
function get_attachments($content, $part = null) {
static $results;
// First round, emptying results
if (is_null($part)) {
$results = array();
}
// Removing first dot (.)
if (substr($part, 0, 1) == '.') {
$part = substr($part, 1);
}
// Checking ifdparameters
if (isset($content->ifdparameters) && $content->ifdparameters == 1 && isset($content->dparameters) && is_array($content->dparameters)) {
foreach ($content->dparameters as $object) {
if (isset($object->attribute) && strtolower($object->attribute) == ‘filename’) {
$results[] = array(
‘type’ => (isset($content->subtype)) ? $content->subtype : ‘’,
‘encoding’ => $content->encoding,
‘part’ => (is_null($part)) ? 1 : $part,
‘filename’ => $object->value
);
}
}
}
// Checking ifparameters
else if (isset($content->ifparameters) && $content->ifparameters == 1 && isset($content->parameters) && is_array($content->parameters)) {
foreach ($content->parameters as $object) {
if (isset($object->attribute) && strtolower($object->attribute) == ‘name’) {
$results[] = array(
‘type’ => (isset($content->subtype)) ? $content->subtype : ‘’,
‘encoding’ => $content->encoding,
‘part’ => (is_null($part)) ? 1 : $part,
‘filename’ => $object->value
);
}
}
}
// Recursivity
if (isset($content->parts) && count($content->parts) > 0) {
// Other parts into content
foreach ($content->parts as $key => $parts) {
get_attachments($parts, ($part.’.’.($key + 1)));
}
}
return $results;
}
?>[/code]
Since I’m not so good with php functions, I can’t figure out how to call this script to do a foreach and grap each attachment and it’s filename and then save it to my server. Something like this:
foreach ($content as $data)
{
file_put_contents($filename, $data);
}
I know that’s not correct but I’m hoping you get my idea.
Thanks!