Advertisement
tetrode

PHP IMAP IDLE

Aug 13th, 2014
914
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.72 KB | None | 0 0
  1. <?php
  2. # @todo
  3. # recursive line checking based on lenght
  4. # check for response RFC
  5. # fread 4096 except mails
  6.  
  7. $login = "first.last@gmail.com";
  8. $password = "p4$$W0rD";
  9.  
  10. if (!($fp = fsockopen('ssl://imap.gmail.com', '993', $errno, $errstr, 15)))
  11. {
  12.     die("Could not connect to host");
  13. }
  14.  
  15. // server greeting
  16. get_line($fp, "/^\* OK/");
  17.  
  18. // unique ID
  19. define('UID', uniqid());
  20. put_line($fp, UID." LOGIN $login $password\r\n");
  21. get_line($fp, "/^".UID." OK/");
  22.  
  23. $msgbox = "INBOX";
  24. put_line($fp, UID." SELECT $msgbox\r\n");
  25. get_line($fp, "/^".UID." OK/");
  26.  
  27. put_line($fp, UID." IDLE\r\n");
  28. get_line($fp, "/^./");
  29.  
  30. while(TRUE)
  31. {
  32.     $response = get_line($fp, "/^./");
  33.     if(preg_match('/([\d]+) EXISTS/', $response, $matches))
  34.     {
  35.         // DONE: OK/NO/BAD
  36.         put_line($fp, "DONE\r\n");
  37.         get_line($fp, "/^./");
  38.  
  39.         // FETCH: OK/NO/BAD
  40.         put_line($fp, UID." FETCH ".$matches[1]." BODY[TEXT]\r\n");
  41.         get_line($fp, "/^./");
  42.         echo time();
  43.  
  44.         put_line($fp, UID." IDLE"."\r\n");
  45.     }
  46. }
  47.  
  48. fclose($fp);
  49.  
  50. function put_line($fp, $line)
  51. {
  52.     echo "sending   $line";
  53.     fwrite($fp, $line);
  54. }
  55.  
  56. function get_line($fp, $expect)
  57. {
  58.     echo ">get_line $expect\r\n";
  59.     $r = "";
  60. echo ".";
  61. $timeout = 10 * 1000000; // 10 s
  62. $timeout = 10 * 10;
  63.     echo  stream_set_blocking($fp, 1);
  64.     echo stream_set_timeout($fp, 0, $timeout);
  65.     $info = stream_get_meta_data($fp);
  66.  
  67.     while ((!feof($fp)) && (!$info['timed_out'])) {
  68. echo ".";
  69.         $line = fgets($fp, 4096);
  70.         $info = stream_get_meta_data($fp);
  71.         echo "received  " . $line;
  72.         $r .= $line;
  73.         if (preg_match($expect, $line)) {
  74.             break;
  75.         }
  76.     }
  77.     return $r;
  78. }
  79.  
  80. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement