Search code examples
phpsqlemailimap

Using PHP & IMAP to get emails not already grabbed


This is more of a question about best practices - I hope that's ok.

I am using PHP and IMAP to grab emails from a Gmail account every 30 minutes. I only want the script to grab emails from 30 minutes ago, so it will never grab the same email twice.

There is a "since" command in the search query:

imap_search($inbox, 'SUBJECT "Ticket #" SINCE "'.date("Y-m-d").'"');

But this will only take a date and not a time.

I can technically do a loop through all emails and only grab emails that are 30 minutes away from the current time:

$email_time = strtotime($overview[0]->date);
$current_time = strtotime('-30 minutes');
if($email_time >= $current_time) {
    ...
}

I don't believe this to be a reliable solution though, because whose to say the emails aren't delayed, or what happens if the server goes down for a few minutes?

Every time the cron job executes the email script, I can store the time in the database and use that time as a reference to check all emails since. But then I need to create a brand new table, just for one field?

I'm thinking there must be a better solution....


Solution

  • Indeed. You should track the UIDs of the messages you download. All new messages that arrive will have a higher UID than any previous message. So just fetch messages with UIDs higher than you already have.