My need: I want to get the count of unread email in my GMail account (or any other email service), and after I get that I need it to be displayed in a webpage on my local PHP server. So I need a scripting language, that would be PHP. But I tried many examples but none of them seems to work. So basically what I want is a PHP script that can access my GMail account and return the count of unread emails to a webpage.
I have tried this script in vain, it always keeps showing "Error" on my webpage.
<?php
function CountUnreadMail($host, $login, $passwd) {
$mbox = imap_open($host, $login, $passwd);
$count = 0;
if (!$mbox) {
echo "Error";
} else {
$headers = imap_headers($mbox);
foreach ($headers as $mail) {
$flags = substr($mail, 0, 4);
$isunr = (strpos($flags, "U") !== false);
if ($isunr)
$count++;
}
}
imap_close($mbox);
return $count;
}
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'username';
$password = 'password';
$count = CountUnreadMail($hostname, $username, $password);
?>
As Chris helped, I tries this script but the only thing that I see is a blank page. Here is another script that I tried in vain:
<?php
function mailCount($host, $login, $passwd) {
$mbox = imap_open($host, $login, $passwd);
$mail = '';
if($mail = imap_check($mbox)) {
return $mail->Nmsgs;
}
}
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'phpimap123'; //GMail username
$password = 'phptesting'; //Password
$count = mailCount($hostname, $username, $password);
echo $count;
?
PS: I have made a GMail account for testing purposes only.
I am running Mac OS X Lion on a MacBook Air. with PHP enabled and running, and I also have MAMP and it is also running.
Try replacing if (!$mbox)
with if ($mbox === FALSE)
You should be doing a specific type check, it is bad practice to test a handle in that manner.
Also, try logging into your account via gmail.com. It is possible you have too many invalid attempts and Gmail wants you to enter a captcha first, which cannot be done via IMAP.
If you're doing it through IMAP why don't you just use:
function mailCount($host, $login, $passwd)
{
$mbox = imap_open($host, $login, $passwd);
$mail = '';
if($mail = imap_check($mbox))
{
return $mail->Nmsgs;
}
}
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'username';
$password = 'password';
$count = mailCount($hostname, $username, $password);
This will give you the unread mail count.
$inbox = imap_open($hostname,$username,$password,OP_READONLY) or die('Cannot connect to Gmail: ' . imap_last_error()); $unread = count (imap_search($inbox, 'UnSeen'));
imap_check will give you: Date, Driver, Mailbox, Nmsgs, Recent (Nmsgs = total messages, Recent = this is NOT unread count but recent)