Search code examples
phpemailimap

Get newly arrived emails from the last sync to the php application using IMAP


I would like to create a php script to fetch the new emails using IMAP and store them in the my database. I want to know how can I identify the new emails which are arrived to the inbox and other mailboxes after the last sync.

The same IMAP email account is connected with outlook and therefore the new emails might have already been seen in the outlook, which might not sync to the PHP Application yet. I cannot use the UNSEEN flag because of the same mailbox is used in multiple places. I want to know which is the best way to the get the new emails by using the last email sync.

Say there is 100 emails in the inbox. my php program sync 50 on the last time. now it have to sync the next 50 emails only. But in those new 50 mails 25 emails are been checked using outlook (already seen). So when I use the UNSEEN flag criteria for the PHP application its only gives the 25 emails which are not read yet, but I should get the 50 emails.

I should be able to use something from the last email sync from PHP application to get the next set. But I don't know which one I should use.


Solution

  • You're perhaps looking for the Unique ID in IMAP protocol. Your server should not change the unique IDs across sessions (that is when you connect the next time to the server), so you can look it up:

    Those numbers have certain properties, I'd say the order they can express as well the uniqueness should help you not to search through all emails:

    Unique identifiers are assigned in a strictly ascending fashion in the mailbox; as each message is added to the mailbox it is assigned a higher UID than the message(s) which were added previously. Unlike message sequence numbers, unique identifiers are not necessarily contiguous.

    When you use thise UIDs, you have to as well make use of UIDVALIDITY as outlined in that section because the UIDs when you store them to the database are based on the value of UIDVALIDITY. In case the UIDVALIDITY changes, you need to re-index the mailbox again.

    Alternative Mailbox

    Alternatively create another mailbox and tell your mailserver on incoming mails to forward a copy to that mailbox. Those mails won't be tagged by the mailclient (Outlook) as you don't share that Mailbox. You then already have a database server (as IMAP could possible count as one for emails), so this is perhaps just the way you want to go anyway.

    Pipe the Mail to your Script

    As another alternative, just configure the mailserver to pipe new emails to a script that inserts these in the database. This is outlined (as well as some other methods) in: