Help Reading from a POP3 Mail Server

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I am trying to get e-mails one at a time from a pop3 mail server.  I can open
the pop3 socket on port 110 using 

        fsockopen(tcp://127.0.0.1, 110, $errno, $errstr) 

and I have no problem logging on to the mail account and issuing the LIST and
RETR commands.

BUT getting the actual email has me stumped.  Using fgets() works OK IF I can
tell it how many lines to expect.  If not, it runs off the end of the file and I
have to cancel the job manually.  If I use the code in the fread() documentation
it does the same thing:

        $message = "";
        while (! feof($mail_sock))
          {
           $message .= fread($mail_sock, 8192);
          }

hangs at the end of the email and I need to cancel manually. Putting an echo
command right after the fread() statement shows that the entire message arrives
correctly before it hangs.

I have tried checking for the ".\r\n" standard pop3 EOF indicator and breaking
out of the while loop when I find it but that is unstable, that combination
occurred during testing in a random email.  Same thing happened using fgets()
before I started trying fread(). 

For completeness, stream_get_contents($mail_sock, 8192) also fails with the same
overrun problem and I can't see the actual data to set an EOF trap. 

I thought maybe the problem would be that the socket was blocking so I framed
the fread() call as:

    stream_set_blocking($mail_sock, false);
    while (! feof($mail_sock))
      {
       $message .= fread($mail_sock, 8192);

        echo "\n" . $message;
      }
    stream_set_blocking($mail_sock, true);

This results in a runaway read of the same email over and over and the programme
needs to be cancelled manually.  Obviously, the feof() command is inactive in
this situation but I don't know why.  (bug???) 

However, if I remove the while loop and run it, I sometimes get the first line
of the email and sometimes nothing; that is, the fread() command doesn't wait
for the server to respond.  

One workaround that I found was to set the socket timeout to a fairly short
value and most of the time this works.  Unfortunately the server occasionally
doesn't respond within the short timeout and the e-mail is truncated.  Longer
timeouts (like 30 seconds) create throughput problems for the application.

At a guess, I suspect that the pop3 server doesn't send any indication at the
end of each e-mail, just stops sending, but I can't prove that and I can't think
of a reliable way to deal with it.

Does anyone have any suggestions?  I've been playing with this for quite a while
without any success.  :-(  






[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux