Google Groups
Subscribe to Software Outsourcing [ Hire Dedicated Group ]
Email:
Visit this group

Saturday, June 2, 2007

Get Email Detail With PHP imap_fetch_overview()

The main PHP function used is the imap_fetch_overview($mbox,"1:$MN",0); in this example it tells PHP to fetch message 1 to $MN ($msgCount = the last message from the connection $mbox).

For each message we retrieve in the main "for loop" some properties.
Thats made with:
$val=$overview[$i];
$msg=$val->msgno;
$from=$val->from;
$date=$val->date;
$subj=$val->subject;
$seen=$val->seen;

$msg is getting the message number that identifies a single message from the mailbox. The first one is 1
$from is getting the senders name
$date is getting the date and time of the arrival in your mailbox.
$subj is getting the subject of the message
$seen is either 0 or 1 if 1 the message body has been retrieved earlier.

Thats practically all we need to know for now to produce a list of all the messages.
The seen property is not used in my example but you could implement it easily with an if statement that writes a not seen message (with property of 0) in bold if you want an overview over new messages especially if you are connecting to a IMAP account.

Now we'll take a look on how to retrive the body of the message.

Body retrieval

To retrieve the body of a message I use a nice script posted in www.php.net I thank the author :-)

function get_mime_type(&$structure) {
$primary_mime_type = array("TEXT", "MULTIPART","MESSAGE", "APPLICATION", "AUDIO","IMAGE", "VIDEO", "OTHER");
if($structure->subtype) {
return $primary_mime_type[(int) $structure->type] . '/' .$structure->subtype;
}
return "TEXT/PLAIN";
}
function get_part($stream, $msg_number, $mime_type, $structure = false,$part_number = false) {

if(!$structure) {
$structure = imap_fetchstructure($stream, $msg_number);
}
if($structure) {
if($mime_type == get_mime_type($structure)) {
if(!$part_number) {
$part_number = "1";
}
$text = imap_fetchbody($stream, $msg_number, $part_number);
if($structure->encoding == 3) {
return imap_base64($text);
} else if($structure->encoding == 4) {
return imap_qprint($text);
} else {
return $text;
}
}

if($structure->type == 1) /* multipart */ {
while(list($index, $sub_structure) = each($structure->parts)) {
if($part_number) {
$prefix = $part_number . '.';
}
$data = get_part($stream, $msg_number, $mime_type, $sub_structure,$prefix . ($index + 1));
if($data) {
return $data;
}
} // END OF WHILE
} // END OF MULTIPART
} // END OF STRUTURE
return false;
} // END OF FUNCTION

?>

source