get attachments from nested imap parts - php

I'm using the below function to get attachments from an email (index $m) on an existing imap connection ($imap)
function parse_parts(&$structure, &$attachments, &$imap, $m, $par){
if(isset($structure->parts) && count($structure->parts) ) {
for($i = 0; $i < count($structure->parts); $i++) {
$attachments[] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
$lstk= array_keys($attachments); $j=end($lstk); // use this instead of $i to avoid overlapping indices when there's sub-parts and recursion
if($structure->parts[$i]->ifdparameters) {
foreach($structure->parts[$i]->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$attachments[$j]['is_attachment'] = true;
$attachments[$j]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters) {
foreach($structure->parts[$i]->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$attachments[$j]['is_attachment'] = true;
$attachments[$j]['filename'] = imap_utf8($object->value);
}
}
}
if($attachments[$j]['is_attachment']) {
if($par==''){
$attachments[$j]['attachment'] = imap_fetchbody($imap, $m, $i+1);
}else{
$attachments[$j]['attachment'] = imap_fetchbody($imap, $m, $par . $i+1);
}
if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
$attachments[$j]['attachment'] = base64_decode($attachments[$j]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
$attachments[$j]['attachment'] = quoted_printable_decode($attachments[$j]['attachment']);
}else{echo "encod:". $structure->parts[$i]->encoding . PHP_EOL; }
}
if(isset($structure->parts[$i]->parts) && count($structure->parts[$i]->parts)){ //if the part contains its own parts, recurse
$prnt = $i;
$prnt = $prnt . '.';
parse_parts($structure->parts[$i], $attachments, $imap, $m, $prnt );
}
}
}
}
the later function which calls this looks like:
$structure = imap_fetchstructure($imap, $m);
$attachments = array();
parse_parts($structure, $attachments, $imap, $m, '');
the standard function works fine, but when it has to recurse (i.e. there are nested parts), the resulting file is not readable, though it does appear to be the correct size. Any idea what i'm doing wrong?
i've tried changing $prnt to
$prnt = $i+1 .'.';
but then, it just outputs an empty file.
i noticed that other people had similar issues here:
imap - get attached file
but their solutions don't appear to work for this email/code.

thank you to IVO GELOV for finding my mistake. final working function:
function parse_parts(&$structure, &$attachments, &$imap, $m, $par){
if(isset($structure->parts) && count($structure->parts) ) {
for($i = 0; $i < count($structure->parts); $i++) {
$attachments[] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
$lstk= array_keys($attachments); $j=end($lstk); // use this instead of $i to avoid overlapping indices when there's sub-parts and recursion
if($structure->parts[$i]->ifdparameters) {
foreach($structure->parts[$i]->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$attachments[$j]['is_attachment'] = true;
$attachments[$j]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters) {
foreach($structure->parts[$i]->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$attachments[$j]['is_attachment'] = true;
$attachments[$j]['filename'] = imap_utf8($object->value);
}
}
}
if($attachments[$j]['is_attachment']) {
if($par==''){
$attachments[$j]['attachment'] = imap_fetchbody($imap, $m, ($i+1));
}else{
$attachments[$j]['attachment'] = imap_fetchbody($imap, $m, $par . ($i+1));
}
if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
$attachments[$j]['attachment'] = base64_decode($attachments[$j]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
$attachments[$j]['attachment'] = quoted_printable_decode($attachments[$j]['attachment']);
}else{echo "encod:". $structure->parts[$i]->encoding . PHP_EOL; }
}
if(isset($structure->parts[$i]->parts) && count($structure->parts[$i]->parts)){ //if the part contains its own parts, recurse
$prnt = $i+1;
$prnt = $prnt . '.';
parse_parts($structure->parts[$i], $attachments, $imap, $m, $prnt );
}
}
}
}

attachment may be inline or external file too.
so we have to get both type of attachments.
$structure = imap_fetchstructure($this->imap, $id);
$fileName = $attachments = array();
/* if any attachments found... */
if (isset($structure->parts) && count($structure->parts)) {
$n = 0;
for($i = 0; $i < count($structure->parts); $i++){
if(isset($structure->parts[$i]->parts) && !empty($structure->parts[$i]->parts) && count($structure->parts[$i]->parts)>0){
for($y = 0; $y < count($structure->parts[$i]->parts); $y++)
{
$attachments[$n] = array('is_attachment' => false,'filename' => '','name' => '','attachment' => '','size' => '','cid' => 0);
if($structure->parts[$i]->parts[$y]->ifdparameters==1) {
foreach($structure->parts[$i]->parts[$y]->dparameters as $object){
if(strtolower($object->attribute) == 'filename'){
$attachments[$n]['is_attachment'] = true;
$fileName[0] = $object->value;
$filename = $this->filterFileName($fileName);
$attachments[$n]['filename'] = $filename;
$attachments[$n]['name'] = $filename;
}
}
}
if($structure->parts[$i]->parts[$y]->ifparameters){
foreach($structure->parts[$i]->parts[$y]->parameters as $object){
if(strtolower($object->attribute) == 'name'){
$attachments[$n]['is_attachment'] = true;
$fileName[0] = $object->value;
$filename = $this->filterFileName($fileName);
$attachments[$n]['name'] = $filename;
$attachments[$n]['filename'] = $filename;
}
}
}
if($attachments[$n]['is_attachment']){
$attachments[$n]['attachment'] = imap_fetchbody($this->imap, $id, ($i+1).'.'.($y+1));
if($structure->parts[$i]->parts[$y]->encoding == 3){ /* 4 = QUOTED-PRINTABLE encoding */
$attachments[$n]['attachment'] = base64_decode($attachments[$n]['attachment']);
}
elseif($structure->parts[$i]->parts[$y]->encoding == 4){ /* 3 = BASE64 encoding */
$attachments[$n]['attachment'] = quoted_printable_decode($attachments[$n]['attachment']);
}
$attachments[$n]['size'] = $structure->parts[$i]->parts[$y]->bytes;
$attachments[$n]['cid'] = ($structure->parts[$i]->parts[$y]->ifid) ? str_replace(array('<', '>'), '', $structure->parts[$i]->parts[$y]->id) : 0;
}
$email['attachments'][] = $attachments[$n];$n++;
}
}else{
$attachments[$n] = array('is_attachment' => false,'filename' => '','name' => '','attachment' => '','size' => '','cid' => 0);
if($structure->parts[$i]->ifdparameters==1){
foreach($structure->parts[$i]->dparameters as $object){
if(strtolower($object->attribute) == 'filename'){
$attachments[$n]['is_attachment'] = true;
$fileName[0] = $object->value;
$filename = $this->filterFileName($fileName);
$attachments[$n]['filename'] = $filename;
$attachments[$n]['name'] = $filename;
}
}
}
if($structure->parts[$i]->ifparameters){
foreach($structure->parts[$i]->parameters as $object){
if(strtolower($object->attribute) == 'name'){
$attachments[$n]['is_attachment'] = true;
$fileName[0] = $object->value;
$filename = $this->filterFileName($fileName);
$attachments[$n]['name'] = $filename;
$attachments[$n]['filename'] = $filename;
}
}
}
if($attachments[$n]['is_attachment']){
$attachments[$n]['attachment'] = imap_fetchbody($this->imap, $id, $i+1);
if($structure->parts[$i]->encoding == 3){/* 4 = QUOTED-PRINTABLE encoding */
$attachments[$n]['attachment'] = base64_decode($attachments[$n]['attachment']);
}elseif($structure->parts[$i]->encoding == 4){ /* 3 = BASE64 encoding */
$attachments[$n]['attachment'] = quoted_printable_decode($attachments[$n]['attachment']);
}
$attachments[$n]['size'] = $structure->parts[$i]->bytes;
$attachments[$n]['cid'] = ($structure->parts[$i]->ifid) ? str_replace(array('<', '>'), '', $structure->parts[$i]->id) : 0;
}
$email['attachments'][] = $attachments[$n];$n++;
}
}
}
public function filterFileName($fileName) {
$newstr = preg_replace('/[^a-zA-Z0-9\-\.\']/', '_', $fileName[0]);
$fileName = str_replace("'", '', $newstr);
return $fileName;
}
after that you have to store this attachments

Related

PHP - IMAP: Save Attachment and rename it

I found this code under this question PHP - IMAP: Save Attachment to Specific Folder and it works really well. Thanks for that.
I need a little change regarding the filename. Currently the attachments will be saved with the original filename. But i need as filename the timestamp of the mail. How I need to change the code to do that?
<?php
function getFileExtension($fileName){
$parts=explode(".",$fileName);
return $parts[count($parts)-1];
}
$imap = imap_open($server, $username, $password) or die("imap connection error");
$message_count = imap_num_msg($imap);
for ($m = 1; $m <= $message_count; ++$m){
$header = imap_header($imap, $m);
//print_r($header);
$email[$m]['from'] = $header->from[0]->mailbox.'#'.$header->from[0]->host;
$email[$m]['fromaddress'] = $header->from[0]->personal;
$email[$m]['to'] = $header->to[0]->mailbox;
$email[$m]['subject'] = $header->subject;
$email[$m]['message_id'] = $header->message_id;
$email[$m]['date'] = $header->udate;
$from = $email[$m]['fromaddress'];
$from_email = $email[$m]['from'];
$to = $email[$m]['to'];
$subject = $email[$m]['subject'];
echo $from_email . '</br>';
echo $to . '</br>';
echo $subject . '</br>';
$structure = imap_fetchstructure($imap, $m);
$attachments = array();
if(isset($structure->parts) && count($structure->parts)) {
for($i = 0; $i < count($structure->parts); $i++) {
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters) {
foreach($structure->parts[$i]->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters) {
foreach($structure->parts[$i]->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($imap, $m, $i+1);
if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
foreach ($attachments as $key => $attachment) {
$name = $attachment['name'];
$contents = $attachment['attachment'];
file_put_contents($name, $contents);
}
//imap_setflag_full($imap, $i, "\\Seen");
//imap_mail_move($imap, $i, 'Trash');
}
imap_close($imap);
?>

PHP - IMAP: Save Attachment to Specific Folder

I found this code that works almost great but I need it to:
1. (MUST) Save the attachments to a specific folder on the server and not where the .php file is.
2. (IF POSSIBLE) Right now the code generates some files that are Zero bytes in size. (I can write something that checks the file-size and then deletes the files that are Zero in size but I would like to stop it from being created in the first place if possible.
<?php
function getFileExtension($fileName){
$parts=explode(".",$fileName);
return $parts[count($parts)-1];
}
$imap = imap_open($server, $username, $password) or die("imap connection error");
$message_count = imap_num_msg($imap);
for ($m = 1; $m <= $message_count; ++$m){
$header = imap_header($imap, $m);
//print_r($header);
$email[$m]['from'] = $header->from[0]->mailbox.'#'.$header->from[0]->host;
$email[$m]['fromaddress'] = $header->from[0]->personal;
$email[$m]['to'] = $header->to[0]->mailbox;
$email[$m]['subject'] = $header->subject;
$email[$m]['message_id'] = $header->message_id;
$email[$m]['date'] = $header->udate;
$from = $email[$m]['fromaddress'];
$from_email = $email[$m]['from'];
$to = $email[$m]['to'];
$subject = $email[$m]['subject'];
echo $from_email . '</br>';
echo $to . '</br>';
echo $subject . '</br>';
$structure = imap_fetchstructure($imap, $m);
$attachments = array();
if(isset($structure->parts) && count($structure->parts)) {
for($i = 0; $i < count($structure->parts); $i++) {
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters) {
foreach($structure->parts[$i]->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters) {
foreach($structure->parts[$i]->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($imap, $m, $i+1);
if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
foreach ($attachments as $key => $attachment) {
$name = $attachment['name'];
$contents = $attachment['attachment'];
file_put_contents($name, $contents);
}
//imap_setflag_full($imap, $i, "\\Seen");
//imap_mail_move($imap, $i, 'Trash');
}
imap_close($imap);
?>
You can write the file to any folder you like, The rename() function can be used for this purpose
http://php.net/manual/en/function.rename.php
rename('image1.jpg', 'del/image1.jpg');
If you want to keep the existing file in the same place you should use copy
http://php.net/manual/en/function.copy.php
copy('image1.jpg', 'del/image1.jpg');
you can use the code after you put_file_contents() to move the file around directories/folders
EDIT: Create file in another directory rather than moving it around after creation
file_put_contents('./myDir/myFile', $file);
Where the . represents the current directory of your project.
Also, remember file_put_contents() does not create folders/directories they need to be existing or you need to create it using mkdir()
Replace
foreach ($attachments as $key => $attachment) {
$name = $attachment['name'];
$contents = $attachment['attachment'];
file_put_contents($name, $contents);
}
with
foreach ($attachments as $attachment) {
file_put_contents($attachment['name'], $attachment['attachment']);
}
and it will save your attachment to your root, from there you can move it as you wish.
You can put the file directly on your desired path like this:
$mypath = '../../myfiles/';
foreach ($attachments as $attachment) {
file_put_contents( $mypath . $attachment['name'], $attachment['attachment']);
}

Fetching email using PHP imap messes up inline embedded images

I made a webmail php class to fetch my domain's webmail.
Everything runs perfectly except that when the email has embedded images (like signatures), the images are fetched with CID in their src and also are treated as attachments.
<img src="cid:auto_cid_2093934881" />
So i end up with a broken source image (in its original place in the email body) and an attachment of the same image that actually works. But i don't need the image to be an attachment, i just want the images to be shown in their places.
Can anyone help me fix this class so it can fetch the images correctly?
Here's my code to get a single email:
<?php
$uid=mysql_real_escape_string($_GET['email_id']);
ini_set("max_execution_time",360);
/* connect to server */
$hostname = '{***.com:143/notls}INBOX';
$username = 'fadi#***.com';
$password = '*******';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to domain:' . imap_last_error());
$overview = imap_fetch_overview($inbox,$uid,0);
$header = imap_headerinfo($inbox, $uid);
$fromaddr = $header->from[0]->mailbox . "#" . $header->from[0]->host;
$webmail = new Webmail();
$message = $webmail->getEmailBody($uid,$inbox);
$attachments = $webmail->extract_attachments($inbox,$uid);
$attach_hrefs = '';
if(count($attachments)!=0){
$target_dir = "emails/".$uid;
if (!is_dir($target_dir)) {
// dir doesn't exist, make it
mkdir($target_dir);
}
foreach($attachments as $at){
if($at[is_attachment]==1){
file_put_contents($target_dir.'/'.$at[filename], $at[attachment]);
$attach_hrefs .='<a target="new" href="'.$target_dir.'/'.$at[filename].'">'.$at[filename].'</a> ';
}
}
}
?>
Here's the webmail class:
<?php
class Webmail{
function getEmailBody($uid, $imap)
{
$body = $this->get_part($imap, $uid, "TEXT/HTML");
// if HTML body is empty, try getting text body
if ($body == "") {
$body = $this->get_part($imap, $uid, "TEXT/PLAIN");
}
return $body;
}
function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false)
{
if (!$structure) {
$structure = imap_fetchstructure($imap, $uid, FT_UID);
}
if ($structure) {
if ($mimetype == $this->get_mime_type($structure)) {
if (!$partNumber) {
$partNumber = 1;
}
$text = imap_fetchbody($imap, $uid, $partNumber, FT_UID);
switch ($structure->encoding) {
case 3:
return imap_base64($text);
case 4:
return imap_qprint($text);
default:
return $text;
}
}
// multipart
if ($structure->type == 1) {
foreach ($structure->parts as $index => $subStruct) {
$prefix = "";
if ($partNumber) {
$prefix = $partNumber . ".";
}
$data = $this->get_part($imap, $uid, $mimetype, $subStruct, $prefix . ($index + 1));
if ($data) {
return $data;
}
}
}
}
return false;
}
function get_mime_type($structure)
{
$primaryMimetype = ["TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER"];
if ($structure->subtype) {
return $primaryMimetype[(int)$structure->type] . "/" . $structure->subtype;
}
return "TEXT/PLAIN";
}
function extract_attachments($connection, $message_number) {
$attachments = array();
$structure = imap_fetchstructure($connection, $message_number);
if(isset($structure->parts) && count($structure->parts)) {
for($i = 0; $i < count($structure->parts); $i++) {
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters) {
foreach($structure->parts[$i]->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters) {
foreach($structure->parts[$i]->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($connection, $message_number, $i+1);
if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
return $attachments;
}
}
?>
Thanks in advance.
Try bellow class for fetch mail body with inline image
Note See get_mail_body($body_type = 'html') method in class to that store mail body inline image to local server you need to change it as you directory layout.
I hope this help you.
$email_message = new Email_message();
$mailbody = $email_message->get_mail_body();
;
class Email_message {
public $connection;
public $messageNumber;
public $bodyHTML = '';
public $bodyPlain = '';
public $attachments;
public $getAttachments = true;
public function __construct($config_data = array()) {
$this->connection = $config_data['connection'];
$this->messageNumber = isset($config_data['message_no'])?$config_data['message_no']:1;
}
public function fetch() {
$structure = #imap_fetchstructure($this->connection, $this->messageNumber);
if(!$structure) {
return false;
}
else {
if(isset($structure->parts)){
$this->recurse($structure->parts);
}
return true;
}
}
public function recurse($messageParts, $prefix = '', $index = 1, $fullPrefix = true) {
foreach($messageParts as $part) {
$partNumber = $prefix . $index;
if($part->type == 0) {
if($part->subtype == 'PLAIN') {
$this->bodyPlain .= $this->getPart($partNumber, $part->encoding);
}
else {
$this->bodyHTML .= $this->getPart($partNumber, $part->encoding);
}
}
elseif($part->type == 2) {
$msg = new Email_message(array('connection' =>$this->connection,'message_no'=>$this->messageNumber));
$msg->getAttachments = $this->getAttachments;
if(isset($part->parts)){
$msg->recurse($part->parts, $partNumber.'.', 0, false);
}
$this->attachments[] = array(
'type' => $part->type,
'subtype' => $part->subtype,
'filename' => '',
'data' => $msg,
'inline' => false,
);
}
elseif(isset($part->parts)) {
if($fullPrefix) {
$this->recurse($part->parts, $prefix.$index.'.');
} else {
$this->recurse($part->parts, $prefix);
}
}
elseif($part->type > 2) {
if(isset($part->id)) {
$id = str_replace(array('<', '>'), '', $part->id);
$this->attachments[$id] = array(
'type' => $part->type,
'subtype' => $part->subtype,
'filename' => $this->getFilenameFromPart($part),
'data' => $this->getAttachments ? $this->getPart($partNumber, $part->encoding) : '',
'inline' => true,
);
} else {
$this->attachments[] = array(
'type' => $part->type,
'subtype' => $part->subtype,
'filename' => $this->getFilenameFromPart($part),
'data' => $this->getAttachments ? $this->getPart($partNumber, $part->encoding) : '',
'inline' => false,
);
}
}
$index++;
}
}
function getPart($partNumber, $encoding) {
$data = imap_fetchbody($this->connection, $this->messageNumber, $partNumber);
switch($encoding) {
case 0: return $data; // 7BIT
case 1: return $data; // 8BIT
case 2: return $data; // BINARY
case 3: return base64_decode($data); // BASE64
case 4: return quoted_printable_decode($data); // QUOTED_PRINTABLE
case 5: return $data; // OTHER
}
}
function getFilenameFromPart($part) {
$filename = '';
if($part->ifdparameters) {
foreach($part->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$filename = $object->value;
}
}
}
if(!$filename && $part->ifparameters) {
foreach($part->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$filename = $object->value;
}
}
}
return $filename;
}
function get_mail_body($body_type = 'html')
{
$mail_body = '';
if($body_type == 'html'){
$this->fetch();
preg_match_all('/src="cid:(.*)"/Uims', $this->bodyHTML, $matches);
if(count($matches)) {
$search = array();
$replace = array();
foreach($matches[1] as $match) {
$unique_filename = time().".".strtolower($this->attachments[$match]['subtype']);
file_put_contents("./uploads/$unique_filename", $this->attachments[$match]['data']);
$search[] = "src=\"cid:$match\"";
$replace[] = "src='".base_url()."/uploads/$unique_filename'";
}
$this->bodyHTML = str_replace($search, $replace, $this->bodyHTML);
$mail_body = $this->bodyHTML;
}
}else{
$mail_body = $this->bodyPlain;
}
return $mail_body;
}
}

How to retrieve Attached Messages from attachment in emails in php?

I am using the below code to retrieve attachments from an email using the imap_fetchstructure. The code works fine for normal attachments like Images, Files, but not Outlook items. See the code below:
$this->msg_cnt = imap_num_msg($this->conn);
$this->TOTAL_MESSAGES = $this->msg_cnt;
$msgs = imap_sort($this->conn, SORTDATE, 1, SE_UID);
$in = array();
$inctr = 0;
foreach ($msgs as $msguid)
{
$msgno = imap_msgno($this->conn, $msguid);
$has_attachment = false;
$ATT_FILES = "";
$attachment_value = "";
$file_name = "";
$structure = imap_fetchstructure($this->conn, $msgno);
$attachments = array();
$log = "Attachments:\r\n\r\n";
if(isset($structure->parts) && count($structure->parts))
{
for($i = 0; $i < count($structure->parts); $i++)
{
$attachments[$i] = array
(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
{
foreach($structure->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$has_attachment = true;
$attachments[$i]['attachment'] = imap_fetchbody($this->conn, $msgno, $i+1);
if($structure->parts[$i]->encoding == 3)
{ // 3 = BASE64
$result = "Found file attachment (QUOTED-PRINTABLE).\r\n\r\n";
file_put_contents("/var/www/html/attachment_logs.txt", $result, FILE_APPEND);
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4)
{ // 4 = QUOTED-PRINTABLE
ob_start();
echo "QUOTED-PRINTED FOUND. CONTENT:\r\n";
var_dump($attachments[$i]);
$result = ob_get_clean();
file_put_contents("/var/www/html/attachment_logs.txt", $result, FILE_APPEND);
$result = "Found email attachment (QUOTED-PRINTABLE).\r\n\r\n";
file_put_contents("/var/www/html/attachment_logs.txt", $result, FILE_APPEND);
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
$attachment_value = $attachments[$i]['attachment'];
if (empty($attachments[$i]['filename']))
$attachments[$i]['filename'] = "".time()."";
$file_name = $attachments[$i]['filename'];
$folder = "/var/www/html/dvxcss/attachments/";
if (!file_exists($folder))
{
mkdir($folder);
}
//WRITE THE ATTACHMENT
ob_start();
var_dump($attachments);
$log .= ob_get_clean();
$log .= "\r\n\r\n#################################\r\n";
file_put_contents("/var/www/html/attachment_logs.txt", $log, FILE_APPEND);
$ATT_FILES .= $file_name.";";
file_put_contents($folder.$file_name, $attachment_value);
}
}
}
$in[$inctr] = array (
'index' => $inctr,
'header' => imap_headerinfo($this->conn, $msgno),
'body' => $this->getBody($msguid, $this->conn),
'structure' => imap_fetchstructure($this->conn, $msgno),
'hasattachment' => $has_attachment,
'attachment' => "$file_name",
'attfiles' => $ATT_FILES
);
$inctr++;
}
The code gets the filename of the attachment and write it into the server.
Question:
How do I fetch Outlook's Email Attachment using php?
Any help will be so much appreciated. Thanks!
UPDATE:
Found out that they are .eml files. These items are attached as .eml files by outlook. I tried to use gmail to check and it gets a file named "noname.eml".
UPDATE:
IMAP- Parsing original headers from a bounced mail
It is called message/rfc822 or text/rfc822 bodypart.

Downloading attachments to directory with IMAP in PHP, randomly works

I found PHP code online to download attachments to a directory using IMAP from here. http://www.nerdydork.com/download-pop3imap-email-attachments-with-php.html
I modified it slightly changing
$structure = imap_fetchstructure($mbox, $jk);
$parts = ($structure->parts);
to
$structure = imap_fetchstructure($mbox, $jk);
$parts = ($structure);
to get it to run properly, as otherwise I got an error about how stdClass doesn't define a property called $parts. Doing that, I was able to download all the attachments. I tested it again recently though, and it didn't work. Well, it didn't work 6 times, worked the 7th, and then hasn't worked since. I'm thinking it has something to do with me screwing up the parts handling, since count($parts) keeps returning 1 for each message, so it's not finding any attachments I think.
Since it downloaded the attachments at one point with no issues, I feel confident that the area things are getting screwed up is right here. Before this block of code is a for loop that goes through each message in the box, and after it is loop that just goes through $parts for each imap structure. Thanks for any help you can provide. I looked at the imap_fetchstructure page on php.net and can't figure out what I'm doing wrong.
Edit: I just double-checked the folder after typing up my question and it all popped up. I feel like I'm going nuts. I hadn't run the code since a few minutes before I started typing this, and it doesn't make sense to me that it would take this long to trigger. I have some 800 messages in the mailbox, but I figured since it printed my statement at the very end of the PHP that all of the file creation work was done.
This is perfect working answer, try this.
This Sample run properly and download all the attachments with no issues.
<?php
set_time_limit(3000);
/* connect to gmail with your credentials */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'YOUR_USERNAME';
$password = 'YOUR_PASSWORD';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$emails = imap_search($inbox, 'FROM "abc#gmail.com"');
/* if any emails found, iterate through each email */
if($emails) {
$count = 1;
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach($emails as $email_number)
{
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,2);
/* get mail structure */
$structure = imap_fetchstructure($inbox, $email_number);
$attachments = array();
/* if any attachments found... */
if(isset($structure->parts) && count($structure->parts))
{
for($i = 0; $i < count($structure->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
{
foreach($structure->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
/* 3 = BASE64 encoding */
if($structure->parts[$i]->encoding == 3)
{
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
/* 4 = QUOTED-PRINTABLE encoding */
elseif($structure->parts[$i]->encoding == 4)
{
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
/* iterate through each attachment and save it */
foreach($attachments as $attachment)
{
if($attachment['is_attachment'] == 1)
{
$filename = $attachment['name'];
if(empty($filename)) $filename = $attachment['filename'];
if(empty($filename)) $filename = time() . ".dat";
$folder = "attachment";
if(!is_dir($folder))
{
mkdir($folder);
}
$fp = fopen("./". $folder ."/". $email_number . "-" . $filename, "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
}
}
}
}
/* close the connection */
imap_close($inbox);
echo "all attachment Downloaded";
?>
About more, see the link
http://www.codediesel.com/php/downloading-gmail-attachments-in-php-an-update/
this is final working sample
<? include('application.php');
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'XX#XX.com';
$password = 'XX';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox, 'FROM "xxx#gmail.com"');
/* if emails are returned, cycle through each... */
if($emails) {
/* begin output var */
$output = '';
/* put the newest emails on top */
rsort($emails);
foreach($emails as $email_number) {
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,2);
$structure = imap_fetchstructure($inbox,$email_number);
pre($overview);
$attachments = array();
if(isset($structure->parts) && count($structure->parts)) {
for($i = 0; $i < count($structure->parts); $i++) {
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => '');
if($structure->parts[$i]->ifdparameters) {
foreach($structure->parts[$i]->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters) {
foreach($structure->parts[$i]->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
} // for($i = 0; $i < count($structure->parts); $i++)
} // if(isset($structure->parts) && count($structure->parts))
if(count($attachments)!=0){
foreach($attachments as $at){
if($at['is_attachment']==1){
file_put_contents($at['filename'], $at['attachment']);
}
}
}
}
// echo $output;
}
/* close the connection */
imap_close($inbox);
?>
Check out this code:
$structure = imap_fetchstructure($mailbox, $index);
$attachments = array();
if(isset($structure->parts) && count($structure->parts)) {
for($i = 0; $i < count($structure->parts); $i++) {
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => '');
if($structure->parts[$i]->ifdparameters) {
foreach($structure->parts[$i]->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters) {
foreach($structure->parts[$i]->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($connection, $message_number, $i+1);
if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
} // for($i = 0; $i < count($structure->parts); $i++)
} // if(isset($structure->parts) && count($structure->parts))
Some bug fixes and improvements on an answer that is perfectly working
$structure = imap_fetchstructure($mailbox, $email_number);
$attachments = [];
foreach ($structure->parts as $part) {
$is_attachment = (isset($part->disposition) && $part->disposition == 'ATTACHMENT');
if ($part->ifdparameters) {
foreach ($part->dparameters as $object) {
if (strtolower($object->attribute) == 'filename') {
$is_attachment = true;
$filename = $object->value;
break;
}
}
}
if ($part->ifparameters) {
foreach ($part->parameters as $object) {
if (strtolower($object->attribute) == 'name') {
$is_attachment = true;
$name = $object->value;
break;
}
}
}
if (!$is_attachment) {
continue;
}
$attachment = imap_fetchbody($mailbox, $email_number, $email_number+1);
if ($part->encoding == 3) {
$attachment = base64_decode($attachment);
} elseif ($part->encoding == 4) {
$attachment = quoted_printable_decode($attachment);
}
$attachments[] = [
'is_attachment' => $is_attachment,
'filename' => isset($filename) ? $filename : '',
'name' => isset($name) ? $name : '',
'attachment' => isset($attachment) ? $attachment : ''
];
}
/* iterate through each attachment and save it */
$folder = "attachment";
if (!is_dir($folder)) {
mkdir($folder);
}
foreach ($attachments as $attachment) {
if (!empty($attachment['name'])) {
$filename = $attachment['name'];
} elseif (!empty($attachment['filename'])) {
$filename = $attachment['filename'];
} else {
$filename = time().'.dat';
}
$destination = './'.$folder.'/'.$email_number.'-'.$filename;
file_put_contents($destination, $attachment['attachment']);
}
count returns 1 (truthy) if input is falsy, so you should not use it inside comparisons in this way
you does not need loop for when you can use foreach: makes things simple
add new item to array attachments only if it is actually useful: it does not make sense to add items that will be skipped later when saving
foreach loops through iterables, and if count is 0 it simply does not loop: no need to check count before foreach
no need to assign $filename and overwrite: just check with comparison, and assign directly the proper value or default case
file_put_contents is identical to calling fopen(), fwrite() and fclose() successively to write data to a file
more robust check on $is_attachment
mkdir folder should stay outside the loop, as the folder is always the same
//may this help you...good luck
date_default_timezone_set('UTC');
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 0);
set_time_limit(3000);
$fName = [];
if ($subject=='xyz subject' || $subject=='xyz subject')$folder_name = $subject;
else$folder_name = substr($subject,stripos($subject,':')+2);
$list = glob('downloads/xyz/'.$folder_name.'/*');
foreach($list as $key => $filename){$explodeName = explode('/', $filename);$fName[] = $explodeName[2];}
foreach($list as $file){if(is_file($file))unlink($file);}
$hostname = '{imap.gmail.com:993/imap/ssl}Inbox';
$username = 'xyz.xyz#xyz.com';
$password = '*******************';
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$emails = imap_search($inbox, 'SUBJECT "'.$subject.'"');
foreach ($emails as $key => $value) {
$overview = imap_fetch_overview($inbox,$value,0);
$message_date = new DateTime($overview[0]->date);
$date = $message_date->format('Ymd');
$message = imap_fetchbody($inbox,$value,2);
$structure = imap_fetchstructure($inbox, $value);
$attachments = [];
if(isset($structure->parts) && count($structure->parts))
{
for($i = 0; $i < count($structure->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
{
foreach($structure->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $value, $i+1);
if($structure->parts[$i]->encoding == 3) //3 = BASE64 encoding
{
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) //4 = QUOTED-PRINTABLE encoding
{
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
foreach($attachments as $attachment)//iterate through each attachment and save it
{
if($attachment['is_attachment'] == 1)
{
$filename = $attachment['name'];
if(empty($filename)) $filename = $attachment['filename'];
if(empty($filename)) $filename = time() . ".dat";
$new_fileName = $date.'-'.$value.'-'.$filename;
if(!in_array($new_fileName, $fName))
{
$folder='./downloads/xyz/'.$folder_name.'/';
if(!is_dir($folder))mkdir($folder);
$fp = fopen("./". $folder ."/". $date . "-". $value."-". $filename, "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
}
}
}
}
imap_mail_move($inbox,$overview[0]->msgno,'xyz_label');
imap_expunge($inbox);
/* ->Always try to read/open the email by subject/or according to need
->Move or Delete Old/not required mail, so that u don't need to search/load lots of email
->Avoiding unnecessary and old email of the same subject , is to move/delete the same.
*/
}
imap_close($inbox);//Never forget to close the connection

Categories