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);
?>

2 Comments

  1. Sloppy code.
    Causes an error.

    Here is the improved version:

    $emails=imap_search($Connection,’BEFORE “‘ .$date. ‘”‘);
    if(is_array($emails)) ​foreach($emails as $email_id) imap_delete($mbox, $email_id);
    imap_expunge($mbox);

Leave a Reply to Walter Hammerschmidt Cancel reply

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