Home > Net >  Check new email in gmail inbox using PHP
Check new email in gmail inbox using PHP

Time:03-10

So my current code is this in PHP:

$mailbox = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', '[email protected]', 'password') or die('Cannot connect to Gmail: ' . imap_last_error());

This code allows PHP to see my email inbox using IMAP and it works fine.

Now my question is, how to make it so that It checks all the new emails in my inbox and outputs "n New Emails!" and marks each of them as seen automatically.

I would really appreciate It If someone were to shed some light on this as I am very new to IMAP and handling emails programmatically in general.

CodePudding user response:

You could use a combination of imap_search1 and imap_setflag_full2

$mailbox = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', '[email protected]', 'password');

// This gives an array of message IDs for all messages that are UNSEEN
$unseenMessages = imap_search($mailbox, 'UNSEEN');

// Keep in mind that imap_search returns false, if it doesn't find anything
$unseenCount = !$unseenMessages ? 0 : count($unseenMessages);
echo "$unseenCount New Emails!\n";

if ($unseenMessages) {
    // The second parameter of imap_setflag_full function is a comma separated string of message IDs
    // It can also be a range eg 1:5, which would be the same as 1,2,3,4,5
    imap_setflag_full($mailbox, implode(',', $unseenMessages), '\Seen');
}
  • Related