PHP delete old messages from IMAP mail account

This script written in PHP will delete emails older than 120 days from an imap email account.

<?php
$days = 120;
$time = strtotime(date("Y-m-d") . " - " . $days  . " days");
$date = date("Y-m-d", $time);

$mbox = imap_open("{mail.mysite.com:143/novalidate-cert}INBOX", "user@mysite.com", "mypassword")
or die("can't connect: " . imap_last_error());

$MC = imap_check($mbox);

$emails = imap_search($mbox,'BEFORE "' . $date . '"');

foreach ($emails as $email_id) {
    imap_delete($mbox, $email_id);
}

imap_expunge($mbox);
?>

Leave a Comment

Your email address will not be published. Required fields are marked *