Deleting messages with PHP IMAP
Posted March 23rd, 2009 in PHP
I've been writing a series about sending Google Analytics data by email and then processing the emails with PHP's IMAP functions. Once the email has been processed you'll probably want to delete the emails from the mailbox afterwards so this email looks at how to delete emails using PHP's IMAP functions.
Deleting a message is really simple:
imap_delete($connection, $msgno);
where $connection is your already established mailbox connection, and $msgno is the number of the message that should be deleted. See my looping through messages post which shows how you would get the message number by either looping through the messges in the mailbox or using the imap_search function to do a search.
The above function will flag the message to be deleted when connecting to an imap mailbox so you'll either need to then call the imap_expunge function to delete it completely or add the CL_EXPUNGE parameter to the imap_close function when you disconnect.
Using imap_expunge:
imap_expunge($connection);
When calling imap_close:
imap_close($connection, CL_EXPUNGE);
Note that when connecting using POP3 instead of IMAP, the deletion flag is not saved between connections so you need to call imap_expunge during the connection (or use the CL_EXPUNGE flag when disconnecting) to actually purge the messages. With IMAP you could instead expunge them on the next connection instead.
A note on Gmail: imap_delete doesn't delete messages when connecting to a Gmail mailbox, it just removes them from the inbox. My next PHP post on Thursday will look at how to move a Gmail message from the inbox into the trash using Gmail.
Related posts:
- Deleting messages with PHP IMAP and Gmail (Thursday, March 26th 2009)
- Parsing Google Analytics data with PHP: A Series (Friday, March 13th 2009)
- PHP IMAP: Looping through messages to find a specific subject (Thursday, March 5th 2009)
- Open a mailbox other than the INBOX with PHP IMAP (Thursday, February 26th 2009)
- Extracting attachments from an email message using PHP IMAP functions (Monday, February 9th 2009)
- Using PHP IMAP functions to download email (Thursday, February 5th 2009)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

