Search code examples
phpimapsynchronization

Sync emails over imap with a local database


For an email history in a php erp system i would like to sync emails with imap with a local mysql database.

It's faster than i thought to download all messages with attachments (about 5 minutes for 6000 messages), but after downloading all messages it would be great to only download the changes. The problem is that i can't rely on the date of the email because the flaggs (seen, flagged, answered, deleted) can change over time.

Is there a possibility to get only the changed emails, what is the best practice for local email clients like thunderbird?

As far as I understand the protocol, there is a server "push" method, but the php script should not be connected all the time, just as a local email client.

This answer was quite useful, so I have to download the headers (without the body) and compare all messages in every request?

Edit

I know that such tools like imapsync already exists, but I would like to do it without external dependencies.


Solution

  • If the purpose is to download all mails from imap server and then periodically check if there is any new email, which was not previously downloaded and saved to db, then I would recommend using PEAR Net_IMAP class.

    PHP native IMAP has not the capability to set/get custom flags but with Net_IMAP class you can do as follows.

    1. Connect to IMAP server
    2. Read message.
    3. Save to DB.
    4. Using Net_IMAP method setFlags, set a custom flag on that message on server. for example

      setFlags('savedToDb')
      

    Thats it. Next iterations connect to IMAP and check all those messages which do not have the flag that you have set. This way you will be able to handle all emails successfully synched between your IMAP and db.