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

Friday, June 1, 2007

POP3 Mail Access Using Php

When you think about writing a mail client in PHP, beware it's fuzzy because of missing documentation on the imap functions in PHP.
PHP uses the imap functions to fetch and handle mailboxes (also POP3) just a matter of how you connect to your mailaccount.

Making the connection

$ServerName = "{localhost/imap:143}INBOX"; // For a IMAP connection (PORT 143)
$ServerName = "{localhost/pop3:110}INBOX"; // For a POP3 connection (PORT 110)

$UserName = "YOUR USERNAME";
$PassWord = "YOUR PASSWORD";

$mbox = imap_open($ServerName, $UserName,$PassWord) or die("Could not open Mailbox - try again later!");
?>

Now we've got a connection to the mailbox.

To retrieve some content from a mailbox we now always use the object $mbox which has many features and almost any of these are more or less documented. You can always find information about it on www.php.net search in functions for imap.

Now to an example on how to retrieve a list of all messages:

Message list

$ServerName = "{localhost/imap:143}INBOX"; // For a IMAP connection (PORT 143)
//$ServerName = "{localhost/pop3:110}INBOX"; // For a POP3 connection (PORT 110)

$UserName = "YOUR USERNAME";
$PassWord = "YOUR PASSWORD";

$mbox = imap_open($ServerName, $UserName,$PassWord) or die("Could not open Mailbox - try again later!");

if ($hdr = imap_check($mbox)) {
echo "Num Messages " . $hdr->Nmsgs ."\n\n

";
$msgCount = $hdr->Nmsgs;
} else {
echo "failed";
}
$MN=$msgCount;
$overview=imap_fetch_overview($mbox,"1:$MN",0);
$size=sizeof($overview);

echo "

";

for($i=$size-1;$i>=0;$i--){
$val=$overview[$i];
$msg=$val->msgno;
$from=$val->from;
$date=$val->date;
$subj=$val->subject;
$seen=$val->seen;

$from = ereg_replace("\"","",$from);

// MAKE DANISH DATE DISPLAY
list($dayName,$day,$month,$year,$time) = split(" ",$date);
$time = substr($time,0,5);
$date = $day ." ". $month ." ". $year . " ". $time;

if ($bgColor == "#F0F0F0") {
$bgColor = "#FFFFFF";
} else {
$bgColor = "#F0F0F0";
}

if (strlen($subj) > 60) {
$subj = substr($subj,0,59) ."...";
}

echo "
\n";
}

echo "<table border='1' bgcolor='$bgColor' > <tr><td colspan='2' >$from</td><td colspan='2' >$subj</td><td class='tblContent' colspan='2'>$date</td></tr></table>";

imap_close($mbox);
?>

This produces a message list where you can read the subject and the date and time for arrival in you mailbox.

Source