1

I am trying to access a IMAP webmail account in order to delete old messages using php. The script I have so far is:

<?php

$del = new DateTime();
$del->modify('-1 month');

$mbox = imap_open("{imap.test.com:993/imap/ssl}INBOX", "username", "password")
 or die("can't connect: " . imap_last_error());

$MC = imap_check($mbox);

// Fetch an overview for all messages in INBOX
$result = imap_fetch_overview($mbox,"1:{$MC->Nmsgs}",0);
foreach ($result as $overview) {
    $date = $overview->date;
    $date = DateTime::createFromFormat('D, d M Y H:i:s O', $date); 

    if($date<$del) {
        imap_delete($mbox,$overview->msgno);
    }

}   
imap_expunge($mbox);
imap_close($mbox);
?>

The code is now correct. But the web hosting service does not allow scripted access to their IMAP server from localhost

2 Answers2

3

You need a semicolon on this line:

imap_expunge($mbox);

when PHP can't be parsed it returns a 500 error.

wogsland
  • 9,106
  • 19
  • 57
  • 93
  • 1
    Likely your folder is really named INBOX... print out some debugging information as you go like how many messages you found... – Max Nov 20 '15 at 21:31
  • It seems that one.com will not allow users to access their IMAP server via scripts. Hence, mission above is impossible... – Morten Repsdorph Husfeldt Nov 20 '15 at 21:49
  • I think you have to mark the messages for deletion before you call `imap_expunge($mbox)` – Maximus2012 Nov 20 '15 at 22:37
  • You may also have to use stunnel to establish a connection with the mailbox and then use something like this: `$mbox = imap_open("{localhost:143/notls}INBOX", $user, $pass);` – Maximus2012 Nov 20 '15 at 22:41
  • Nevermind, I think you are already doing the thing about marking a message to be deleted before calling imap_expunge(). – Maximus2012 Nov 20 '15 at 22:44
1

Try marking it for deletion before expunging, that worked for me.

imap_delete($mbox, 1);

imap_expunge($mbox);
g4ost
  • 100
  • 8