Imap Basics

I explain how to delete or move mails from a mail account through a script.

First you should setup a connection. This should look like this:


  /* connect to server  */
  $hostname = '{123.mailserver.com:143}'; 
  $username = 'your@login.com';
  $password = 'top_secreted_69';

  /* try to connect */
  $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to mailbox: ' . imap_last_error());

This creates an imap stream to your inbox folder. Its equivalent to:


   /* try to connect */
  $inbox = imap_open($hostname . 'INBOX',$username,$password) or die('Cannot connect to mailbox: ' . imap_last_error());

You may also create a stream to a specific folder. A foldername is of the from "{hostname}Foldername". You may checkout your available folders with


  $mailboxes = imap_list($inbox, $hostname, '*');

If you want to see all emails from your folder `ToDo` you might create the imap stream for that folder through:


   /* try to connect */
  $toDo_folder = imap_open($hostname . 'ToDo',$username,$password) or die('Cannot connect to mailbox: ' . imap_last_error());

We can now iterate through all emails in the ToDo folder like this:


   $emails = imap_search($toDo_folder,'ALL');

   //emails is false if folder is empty
   if($emails) {
        /* for every email... */
        foreach($emails as $email_number) {
            // get message of mail
            $message = imap_body($inbox,$email_number,2);
            // get head
            $head    = imap_headerinfo($inbox, $email_number,2);

One may now check from whom the mail was send


   if(in_array(strtolower($head->from[0]->mailbox),["postmaster","mailer-daemon"] )){
    //.... 
   }

or use some regex to find specfic details in the mails message


   preg_match_all('/To:[^<]*<([^>]*)>/',$message, $matches);

One can also delete emails. First you need to mark a email as deleted, and then you have to confirm deletion:


   // mark email as delete-able
   imap_delete($toDo_folder, $email_number);

    //actually delete mail
   imap_expunge($toDo_folder);

One may also move an email to a folder `important`:


   // copy mail to important and mark as delete
   imap_mail_move($toDo_folder, $email_number, 'important');

    //actually delete mail
   imap_expunge($toDo_folder);

Leave a comment

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