RE: IMAP :- How to download the attachment if any.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Roshan, I use this code to read Exchange mailboxes and extract the message
body with the PEAR standalone MIME_DECODE and IMAP classes :-


<?php

require_once("config.php");
require_once("functions.php");

require_once($coreRootPath . "core/database_class.php");
require_once($coreRootPath . "core/mimedecode_class.php");
require_once($coreRootPath . "core/IMAP_class.php");
require_once($coreRootPath . "core/users_class.php");

require_once($coreRootPath . "core/misc_class.php");
$coreMisc = new coreMisc();

$db = new coreDatabase();
$db->connect($coreDatabase);

$coreUsers = new coreUsers();


if ($_SERVER['argc'] === 0) {
        // assume running under browser
        $_br = "<br>\n";
        $mode = "browser";
} else {
        // assume running on command line
        $_br = "\n";
        $mode = "cli";
}

// set up defaults
$action = "update";                     //      report / update(default)
$debug = false;                         //      debugging
$loop = true;                           //      used to force main checking
loop to continue
$hibernate = 300;                       //      number of seconds to
hibernate before checking mailbox

loadParams();

while($loop = true) {
        message("Connecting to email server '" . $coreDatabase["imap_host"] .
"'....");
        $imap = new
Net_IMAP($coreDatabase["imap_host"],$coreDatabase["imap_port"]);

        //      Turn on protocol debug feature
        if ($debug) {
                $imap->setDebug();
                $imap->setUnparsedResponse(true);
        }


        message("Logging onto email server '" . $coreDatabase["imap_host"] .
"'....");

        if (PEAR::isError($ret =
$imap->login($coreDatabase["imap_user"],$coreDatabase["imap_password"]))) {
            die("Unable to login! reason:" . $ret->getMessage() . "$_br");
        }

        $imap->selectMailbox('inbox');

        $mblist = $imap->examineMailbox("INBOX");
        $first_unread = (array_key_exists("UNSEEN",$mblist)) ?
$mblist['UNSEEN'] : false;

        $num_messages = $imap->getNumberOfMessages("inbox");
        message("There are $num_messages messages in 'inbox'");

        if ($first_unread) {
                message("The first unread message is message
'$first_unread'");
                showSummary($imap);
        }

        $imap->selectMailbox('inbox');

        if ($first_unread) {

                for ($i = $first_unread; $i <= $num_messages; $i++) {

                        if ($imap->isSeen($i)) {
                                message("Message $i has already been
read...ignoring");
                        } else {
                                message("Message $i is unread");

                                if (!$bodyText = getText($imap,$i)) {
                                        emailBad($imap,$i);     // if bad,
send a message to say a bad email
                                                                // was found,
and update message as read

                                        if ($action == "update") {
 
$imap->selectMailbox('inbox');          // switch on read/write
                                                if (!$imap->addSeen($i))
die("Error setting message as unread - " . $ret->getMessag;
                                                message("Message $i marked as
read");
                                        }

                                        continue;
                                }

                                message("Decoded text: \n<pre>" . $bodyText .
"</pre>");
                                $imap->selectMailbox('inbox');          //
switch on read/write

                                if ($action == "update") {
                                        $userDetails = array();
                                        storeEmail($imap,$i,$bodyText);

                                        if (!$imap->addSeen($i)) die("Error
setting message as unread - " . $ret->getMessage() . $_;
                                        message("Message $i marked as read");
                                }
                        }
                }
        } else {
                message("All messages have already been read");
        }


        // $imap->deleteMsg(4);
        message("Disconnecting from email server");
        $imap->disconnect();

        $logicalCheck['WEBDIARY$STATUS'] = array('RUN','RUNNING');
//      $logicalCheck['MONI$PROCESSES'] = 'RUNNING';
        if(!$coreMisc->hibernate($logicalCheck,$hibernate)) break;
}

message("Exiting....");
exit(0);


// ********************** Functions used in Email Download scripts
**********************



function htmlspecialchars_decode($text) {

        // convert text characters back into HTML entities, e.g. '&' to
'&amp;'

        $tmp = $text;
        $tmp = strtr($tmp,
array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
        $tmp = str_replace("&nbsp;"," ",$tmp);

        return $tmp;
}



function trim_crlf($text) {

        // Remove any extra line feeds from the start and end of the text

        $tmp = $text;

        for ($i=0; $i < strlen($tmp); $i++) {
                if (substr($tmp,0,1) == "\n") {$tmp =
substr($tmp,1,strlen($tmp)); continue;}
                if (substr($tmp,0,1) == "\r") {$tmp =
substr($tmp,1,strlen($tmp)); continue;}
                break;
        }

        for ($i = (strlen($tmp)-1); $i > 0; $i--) {
                if (substr($tmp,$i,1) == "\n" or substr($tmp,$i,1) == "\r" or
substr($tmp,$i,1) == " ") continue;

                $tmp = substr($tmp,0,$i+1);
                break;
        }

        return $tmp;
}



function message($text) {

        // Output a message to the screen, prefixed with the date and time
        // If the program is being run interactively, HTML tags will be
converted first

        global $_br, $mode;

        if ($mode == "cli") {
                // echo html2txt(date("d-m-Y H:i:s") . "> " . $text . $_br);
                echo strip_tags(date("d-m-Y H:i:s") . "> " . $text . $_br);
        } else {
                echo date("d-m-Y H:i:s") . "> " . $text . $_br;
        }
}


function showSummary($msgobject) {

        // Display a summary of email messages in the 'inbox'

        global $_br;

        $num_messages = $msgobject->getNumberOfMessages("inbox");

        $fao1 = "%-25.25s %-30.30s %-30.30s %8.8s %-4.4s %-20.20s %s";

        $line = sprintf($fao1, "Date", "From", "To", "Size", "Read",
"Mimetype", "\n");

        for ($i = 1; $i <= $num_messages; $i++) {
                $summary = $msgobject->getSummary($i);
                $summary = $summary[0];

                $seen = ($msgobject->isSeen($i) ? "Y" : "");

                $line .= sprintf($fao1,
                                $summary['DATE'],
                                $summary['FROM'][0]['EMAIL'],
                                $summary['TO'][0]['EMAIL'],
                                $summary['SIZE'],
                                $seen,
                                $summary['MIMETYPE'],
                                "\n");

                // echo "<pre>"; var_dump($summary); echo "</pre>";
        }
        message("Displaying mailbox summary" . $_br . "<pre>" . $line .
"</pre>");
}



function getText($msgobject,$msgid) {

        // Attempt to extract the text from an email message
        // 'false' will be returned if the extracts is unsuccessful

        message("Decoding message '$msgid'");

        $msgobject->examineMailbox('inbox');
        $body = $msgobject->getMsg($msgid);

        $decoder = new Mail_mimeDecode($body);

        $params = array(
            'include_bodies' => TRUE,
            'decode_bodies'  => TRUE,
            'decode_headers' => TRUE);
            
        $decoded = $decoder->decode($params);

        // predump($decoded,"Decoded Message");

        if ($decoded->ctype_primary == "text" and $decoded->ctype_secondary
== "plain") {
                return trim_crlf($decoded->body);
        }

        if ($decoded->ctype_primary == "text" and $decoded->ctype_secondary
== "html") {
                $decodedParts = $decoded->body;
                $decodedParts = html2txt($decodedParts);
                $decodedParts = htmlspecialchars_decode($decodedParts);
                $decodedParts = trim_crlf($decodedParts);

                // message("<pre>"); var_dump($decodedParts);
message("</pre>");
                return $decodedParts;
        }

        // message("<pre>"); var_dump($decoded); message("</pre>");

        if ($decoded->ctype_primary == "multipart" and
$decoded->ctype_secondary == "related") {

                $textPart = findTextPart($decoded->parts);
                if ($textPart === null) {
                        message("No text part found - $textPart");
                        return false;           // No text part found
                }

                $decodedParts = $decoded->parts[$textPart]->body;
                $decodedParts = html2txt($decodedParts);
                $decodedParts = htmlspecialchars_decode($decodedParts);
                $decodedParts = trim_crlf($decodedParts);

                // message("<pre>"); var_dump($decodedParts);
message("</pre>");
                return $decodedParts;
        }

        message("Unable to decode message - dumping data instead: \n<pre>");
        var_dump($decoded);
        message("</pre>");

        return false;


}



function findTextPart($parts) {

        // Where a message is 'multi-part', attempt to find a text or HTML
part containing the message
        // return 'null' if no message can be found, i.e. only contains
images

        for ($i = 0; $i < count($parts); $i++) {
                if ($parts[$i]->ctype_primary == "text" and
$parts[$i]->ctype_secondary == "plain") return $i;
                if ($parts[$i]->ctype_primary == "text" and
$parts[$i]->ctype_secondary == "html") return $i;
        }

        return null;    // Could not find a text part
}


function emailBad($msgobject,$msgid) {

        global $coreAdminEmail;

        $summary = $msgobject->getSummary($msgid);
        $summary = $summary[0];

        $msgFrom = $summary['FROM'][0]['EMAIL'];
        $msgSubject = $summary['SUBJECT'];

        $recipient = $coreAdminEmail;
        $subject = "Failure processing WebDiary email";
        $message = "WebDiary was unable to process an email.

The messages was sent from '$msgFrom' with a subject line of '$msgSubject'";
        sendEmail($recipient,$subject,$message);
        return;
}



function loadParams() {

        // Load parameters from command line or query string

        global  $action,
                $debug;

        // if running in CLI mode, load params from command line

        if ($argv = $_SERVER['argv']) {
                foreach ($argv as $key => $value) {
                        if ($key == 0) continue;                // ignore
script filename parameter
                        $param_pair = explode("=",$value);
                        $string = '$' . $param_pair[0] . ' = "' .
$param_pair[1] . '";';
                        // echo "$string\n";
                        eval($string);
                        message("Loading parameter -> " . $param_pair[0] . ":
" . $param_pair[1]);
                }
        }

        // if running in browser mode, load params from command line

        // *** to be written ***
}




function html2txt($document){

        // Convert HTML to text, stripping out style tags, JavaScript tags,
comments, and HTML tags.
        // The function calls in the html2text class to do most of the
complicated work.


        $text = $document;

        require_once("core/html2text_class.php");

        $search = array(
                '@<script[^>]*?>.*?</script>@si',               // Strip out
javascript
                '@<!DOCTYPE[^>]*?>@si',                         // Strip out
doctype tags
                '@<style[^>]*?>.*?</style>@siU',                // Strip
style tags properly
                '@<![\s\S]*?--[ \t\n\r]*>@'                     // Strip
multi-line comments including CDATA
                );

        $text = preg_replace($search, '', $text);

        $htmlToText = new Html2Text ($text, 80); // 80 columns maximum
        $text = $htmlToText->convert();
        return $text;

        /*      this code replaced by html2text class

        $text = $document;
        $text = str_replace("<br>","\r\n",$text);
        $text = str_replace("<BR>","\r\n",$text);

        $search = array('@<script[^>]*?>.*?</script>@si',  // Strip out
javascript
               '@<style[^>]*?>.*?</style>@siU',    // Strip style tags
properly
               '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
               '@<![\s\S]*?--[ \t\n\r]*>@'        // Strip multi-line
comments including CDATA
        );

        $text = preg_replace($search, '', $text);
        return $text;
        */
}



function storeEmail($msgobject,$msgid,$bodyText) {

        global  $userDetails,
                $coreUsers,
                $db;

        $summary = $msgobject->getSummary($msgid);
        $summary = $summary[0];
        // predump($summary);

        if ($userDetail =
$coreUsers->loadUserByEmail($db,$summary['FROM'][0]['EMAIL'])) {
                $userDetails['name'] = $userDetail['name'];
        } else {
                $userDetails['name'] = $summary['FROM'][0]['PERSONAL_NAME'];
        }

        $aryDetails['title'] = $summary['SUBJECT'];
        $aryDetails['description'] = $bodyText .
"\n\n******************************\n**  Automatically Inserted
**\n*************;
        $aryDetails['alert'] = "Informational";

        // predump($userDetails);
        // predump($aryDetails);

        addEvent($aryDetails);                  // store the email message in
the database
}



?>

 




-----Original Message-----
From: php-objects@xxxxxxxxxxxxxxx [mailto:php-objects@xxxxxxxxxxxxxxx] On
Behalf Of Roshan Shahare
Sent: 04 September 2007 11:59
To: roshan Shahare
Subject:  IMAP :- How to download the attachment if any.

Hi All,
   
  I want to open a mssage using PHP ( IMAP ). How should I download the
attachment if there is any with the email message.
   
  Please send me the code.
   
   
   
  <?php
   $imap = imap_open("{localhost/pop3}INBOX", "username", "password") or
die("can't connect: ".imap_last_error());
   $message_count = imap_num_msg($imap); echo "Total Messages :-
".$message_count; echo "<br>";
   for ($i = 1; $i <= $message_count; ++$i) {
      $header = imap_header($imap, $i);
      //$body = trim(substr(imap_body($imap, $i), 0, 100));
   $body = imap_body($imap, $i);
      $prettydate = date("jS F Y", $header->udate);
        if (isset($header->from[0]->personal)) {
         $personal = $header->from[0]->personal;
      } else {
         $personal = $header->from[0]->mailbox;
      }
        $email = "$personal
<{$header->from[0]->mailbox}@{$header->from[0]->host}>";
      echo "On $prettydate, $email said \"$body\".\n";
   }
     imap_close($imap);
?>

   
   

       
---------------------------------
 Try the revolutionary next-gen Yahoo! Mail. Click here.

[Non-text portions of this message have been removed]



PHP Data object relational mapping generator http://www.metastorage.net/
Yahoo! Groups Links




***********************************************************************************
Any opinions expressed in email are those of the individual and not necessarily those of the company. This email and any files transmitted with it are confidential and solely for the use of the intended recipient 
or entity to whom they are addressed. It may contain material protected by attorney-client privilege. If you are not the intended recipient, or a person responsible for delivering to the intended recipient, be advised that you have received this email in error and that any use is strictly prohibited.

Random House Group + 44 (0) 20 7840 8400
http://www.randomhouse.co.uk
http://www.booksattransworld.co.uk 
http://www.kidsatrandomhouse.co.uk
Generic email address - enquiries@xxxxxxxxxxxxxxxxx

Name & Registered Office:
THE RANDOM HOUSE GROUP LIMITED
20 VAUXHALL BRIDGE ROAD
LONDON
SW1V 2SA
Random House Group Ltd is registered in the United Kingdom with company No. 00954009, VAT number 102838980
***********************************************************************************


[Index of Archives]     [PHP Home]     [PHP Users]     [PHP Soap]     [Kernel Newbies]     [Yosemite]     [Yosemite Campsites]

  Powered by Linux