Mail Cleaner
I have a webhosting, where I have some mail addresses. As I do not want to check them regularly, I simply activated forwarding for all addresses to my main mailbox and deactivated the mailboxes for these addresses. From my main account I can send mails over these addresses via SMTP. This worked, until i switched to a newer webhosting the other day. Now it is not possible to send mails via SMTP without having a mailbox. This leads to the problem, that the mails will be stored in the mailbox although they get forwarded. So, I must check these mailboxes from time to time to clean them up. This is additional work and not as comfortable as it was before.
I searched for a solution and discovered, that my webhosting can run scripts at given times like cron jobs. One type of scripts it can run is PHP. So, I decided to use PHP IMAP to check my mailbox once a day to delete all mails in the inbox which are older than seven days. This behavior will give me a week of backups if anything goes wrong with the forwarding of the mails. All other folders of the mailbox will simply be emptied every day. Normally they should not contain any mails. And here is the simple script, which does the work:
<?php
// Server data
$srv = '{mail.mydomain.tld}';
$usr = 'myusername';
$pw = 'mypassword';
// Names of the different mailboxes
$mailboxNames=array('INBOX','Archives','Trash','Drafts','Sent','Spam');
foreach($mailboxNames as $mb) {
// When INBOX, then get all mails older than a week
if($mb === 'INBOX') {
// Make a normal open, because INBOX is the first
$mailbox = imap_open($srv.$mb, $usr, $pw) or die(implode(", ", imap_errors()));
$emails = imap_search($mailbox,'BEFORE '. date("Y-m-d", strtotime("-7 days")));
}
// From the other mailboxes always get all mails
else{
// Here reopen can be used, because INBOX was opened as first one
imap_reopen($mailbox, $srv.$mb) or die(implode(", ", imap_errors()));
$emails = imap_search($mailbox,'ALL');
}
// Here the deletion happens, if there are mails found in the mailbox
if($emails) {
$allMsgIds = implode(",", $emails);
imap_setflag_full($mailbox, $allMsgIds, "\\Deleted");
imap_expunge($mailbox);
}
}
imap_close($mailbox);
?>