Home / Deleting messages with PHP IMAP and Gmail

Deleting messages with PHP IMAP and Gmail

My last PHP post looked at how to delete email messages using PHP’s IMAP functions. This is straight forward on a regular POP3 or IMAP mail server but deleting a message when connected to Gmail just removes it from the inbox and it’s still available in "All Mail" rather than being moved into the trash. This post looks at how to move an email into Gmail’s trash with PHP IMAP.

Using imap_delete will simply remove the message from the inbox but it will still be available in "All Mail" and won’t be in the trash:

imap_delete($connection, $msgno);

So instead the email message must be moved into the trash using the imap_mail_move function. The second parameter for this function takes a range/list and not a single message number, so to move $msgno you need to set the range as "$msgno:$msgno" like so:

imap_mail_move($connection, "$msgno:$msgno", '[Google Mail]/Trash');

The actual name of the trash folder will vary depending on the language settings. For example I have Gmail set to using "English (UK)" so the trash folder is actually called the "Bin" and to move messages into it requires this instead:

imap_mail_move($connection, "$msgno:$msgno", '[Google Mail]/Bin');

I’ve also seen people refer to the bracketed part as [Gmail] instead of [Google Mail] so it would pay to use the imap_list() function to work out exactly what the trash folder is called and assigning it to a variable. An example of doing this can be found in my Open a mailbox other than the INBOX with PHP IMAP post.