In my last post I described the basics of PHP’s fsockopen. This script is far from perfect and only contains minimal error checking however it illustrates the basics of fsockopen in action communicating with a POP3 server. More information on the POP3 protocol can be found here
define(”POP3_TIMEOUT”, 8);
define(”POP3_SERVER”, “mail.apnicsolutions.com”);
define(”POP3_PORT”, 110);
define(”POP3_USER”, “nobody@adamsinfo.com”);
define(”POP3_PASS”, “secret”);
define(”READ_BUFFER”, 128);
function check_response($response)
{
$r = Array();
$r = explode(” “, $response);
return ($r[0] == “+OK”) ? true : false;
}
function communicate($fp, $send)
{
$response = “”;
echo “> ” . $send;
fwrite($fp, $send);
while(substr($response, (strlen($response)-1), 1) != “\n”)
{
$this_line = fgets($fp, READ_BUFFER);
$response .= $this_line;
}
return “< ” . $response;
}
$resource = fsockopen(POP3_SERVER, POP3_PORT, $errno, $errstr, POP3_TIMEOUT);
if (!$resource)
{
echo “Connect failed: ” . $errstr . “(” . $errno . “)<br />\n”;
} else {
//We should have a POP3 banner at this point
$v = fgets($resource, READ_BUFFER);
echo “< ” . $v . “\n”;
//Send username and password
echo communicate($resource, “USER ” . POP3_USER . “\n”);
echo communicate($resource, “PASS ” . POP3_PASS . “\n”);
echo communicate($resource, “LIST\n”);
$messages = 0;
$this_line = “”;
while($this_line != “.\r\n”)
{
$this_line = fgets($resource, READ_BUFFER);
echo “< ” . $this_line;
$messages++;
}
$messages–;
echo “You have: ” . $messages . ” messages. I’ll retrieve the first one!\n”;
echo communicate($resource, “RETR 1\n”);
$this_line = “”;
while($this_line != “.\r\n”)
{
$this_line = fgets($resource, READ_BUFFER);
echo “< ” . $this_line;
}
echo communicate($resource, “QUIT\n”);
fclose($resource);
}
?>
This produces the following output:
> USER nobody@adamsinfo.com
< +OK Password required.
> PASS secret
< +OK logged in.
> LIST
< +OK POP3 clients that break here, they violate STD53.
< 1 1220
< 2 1550
< 3 1350
< 4 1138
< 5 1038
< 6 15989
< .
You have: 6 messages. I’ll retrieve the first one!
> RETR 1
< +OK 1220 octets follow.
< Return-path: test@adamsinfo.com
###CUT 80 LINES###
< .
> QUIT
< +OK Bye-bye.
I cut the 80 lines of message to avoid an unnecessarily long post!
Tags: fsockopen, PHP, pop3 client
Hey there,
I tried pretty much the same.
I heard fsockopen() works with ssl too…
so theoretically I should be able to connect to pop.gmail.com on 995. but am not able to…
i don’t get the “pop3 banner” from it..
(openssl is enabled and server address with prefix ssl:// throws an error ssl wasn’t recognised…
any help?