2.8.1.6. Removing old emails from the mailbox

Warning!

With a large mailbox volume, the script may not have time to delete messages in one pass and may need to be run again.

The script allows you to delete messages for a certain time interval, which can be specified relative to the current day or fixed dates.

  1. <?php
  2. $Host = isset($argv[1]) ? $argv[1] : "mail.adm.tools:143";
  3. $User = isset($argv[2]) ? $argv[2] : "user@example.com";
  4. $Password = isset($argv[3]) ? $argv[3] : "example_password";
  5. $Before = isset($argv[4]) ? date("Y-m-d", strtotime($argv[4])) : date("Y-m-d", strtotime("-1 year"));
  6. $After = isset($argv[5]) ? date("Y-m-d", strtotime($argv[5])) : date("Y-m-d", strtotime("1970-01-01")); //Older date
  7.  
  8. $Before = 'BEFORE "' . $Before . '"';
  9. $After = 'SINCE "' . $After . '"';
  10.  
  11. $mbox = imap_open("{" . $Host . "/novalidate-cert}INBOX", $User, $Password) or die("Can't connect: " . imap_last_error());
  12.  
  13. try {
  14. if (empty(imap_check($mbox))) {
  15. throw new Exception("Error is occurred");
  16. }
  17. $emails = imap_search($mbox, "$Before $After");
  18. if (empty($emails)) {
  19. throw new Exception("Don't have mail " . strtolower($Before));
  20. }
  21. foreach ($emails as $email_id) {
  22. imap_delete($mbox, $email_id);
  23. '/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m',
  24. imap_fetchheader($mbox, $email_id),
  25. $matches
  26. );
  27. $headers = array_combine($matches[1], $matches[2]);
  28. print_r("$email_id : " . imap_utf8($headers['Subject']) . " => " . $headers['Date'] . "\n<br>");
  29. }
  30. imap_expunge($mbox);
  31. echo "Deleted " . count($emails) . " letters " . strtolower($Before) . "\n";
  32. } catch (Exception $e) {
  33. echo $e->getMessage(), "\n";
  34. }

The data required for the script to work can be specified both in the script itself and in the command line at startup:

  • Hostaddress and port IMAPserver.
  • Usertitle mailbox.
  • Passwordpassword mailbox.
  • Before — letters earlier than the specified date will be deleted. The date can be specified by replacing -1 year for a specific date, in the format YYYY-MM-DD (2010-02-23) or subtracting a certain amount of time from the current date in the format -1 year or -1 month or -1 day.
  • After — letters after the specified date will be deleted. The date can be specified by replacing 1970-01-01 for a specific date, in the format YYYY-MM-DD (2010-02-22) or subtracting a certain amount of time from the current date in the format -1 year or -1 month or -1 day.

Running the script in console or task cron executed by a command of the form:

/usr/local/bin/php /home/example/file.php mail.adm.tools:143 admin@example.com "password" "2022-03-24" "2015-04-28"
Content