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:
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.
When calling imap_close:
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.