Search code examples
phpemailzend-frameworkgmailimap

Attaching labels to messages in Gmail via IMAP using code


concerning Gmail labels - what are they technically speaking. I mean through imap connection I can access a gmail mailbox and go through the emails however let say I wish to create a label and attach it to the emails as I loop through them using code - how can I do that in code? I'm using php - and Zend Framework.

EDIT ===

Thanks for the replies so its now clear that labels are treated like folders in this respect however I've tried the Zend_Mail_Storage_Imap class functions with interesting results. If I try the Zend_Mail_Storage_Imap:moveMessage function - it removes the message from wherever it is and literally attaches a label to it meaning if I wish to attach a label foo to my message it removes it form the inbox and attaches the label foo. However if I use Zend_Mail_Storage_Imap::copyMessage that does the trick.

However I'm wondering here that doesn't this literally make a duplicate copy of the message and you end up with more than one duplicate message right here?

Also what if I need to select all the messages that are attached with a certain label or in this case within a certain folder?


Solution

  • Re: concerning Gmail labels - what are they technically speaking.

    Since IMAP doesn't have the concept of "labels", there is a mapping, more or less, between GMail "labels" and IMAP "folders" Here is the best doc I found on it. But what really helped me in creating my programmatic IMAP interaction with GMail was experimentation.

    For example, the preset labels have IMAP folder names of

    Human name -- IMAP Folder name
    Drafts -- [Gmail]/Drafts
    Sent Mail -- [Gmail]/Sent Mail
    Spam -- [Gmail]/Spam
    Starred -- [Gmail]/Starred
    Trash -- [Gmail]/Trash
    

    Added--

    Re: create a label and attach it to the emails as I loop through them using code - how can I do that in code?

    To create a label, use the Imap 'create folder' operation.

    Use the Imap copy operation to add a label to a message.

    To remove the message from the GMail Inbox, I am 90% sure that you add the IMAP Flag 'Deleted'. -- But please experiment with this first. It is not clear to me which label(s) are removed when you set the deleted flag. In my tests, the message only had 1 label (Inbox) when I applied the deleted flag.

    Here is the code I use for moving a GMail message from Inbox to the Trash folder:

    # Ruby code...
    imap.store(message_id, "+FLAGS", [:Deleted]) # rm inbox label
    imap.copy(message_id, "[Gmail]/Trash")       # add trash label