#!/usr/bin/php
<?php
    // (c) 2009 plugdev @ sub.noloop.net - http://plug.noloop.net
    function speak($text) {
       echo ">> ".$text."\n";
       $arg = escapeshellarg(" ".$text); // space means do not treat as filename
       system("aoss flite ".$arg);
    }    
    function fail($err) {
       echo $err."\n";
       speak("Error: ".$err);
       exit(1);
    }

    $imap = imap_open('{imap.example.com:993/imap/ssl/novalidate-cert}mailbox','username','password');
    if (!is_resource($imap)) {
       fail("Could not connect to mail server");
    } 
 
    $newmail = imap_search($imap, 'UNSEEN');
    if (!is_array($newmail)) {
      speak("There are no new messages.");
    }
    else {
       $mailcount = count($newmail);
       if ($mailcount == 1) {
           speak("There is one new message.");
       }
       else {
           speak("There are $mailcount new messages.");
       }
       $msginfos = imap_fetch_overview($imap, join(',',$newmail));
       if (!is_array($msginfos)) {
           fail("IMAP fetch overview failed to return message information");
       }
       $mailidx = 1;
       foreach ($msginfos as $msginfo) {
           $from_o = imap_mime_header_decode($msginfo->from);
           $from = '';
           foreach ($from_o as $s) {$from .= ' '.$s->text;}
           $subj_o = imap_mime_header_decode($msginfo->subject);
           $subj = '';
           foreach ($subj_o as $s) {$subj .= ' '.$s->text;}
           speak("Message number $mailidx:\n  From: {$from}.\n  Subject: {$subj}.\n.");
           $mailidx++;
       }
    }
    speak("Have a nice day!");
    imap_close($imap);