当前位置: 首页 > 编程文章 >

PHP Socket POP3客户端类实现详解

PHP Socket POP3客户端类实现详解

作者:沈景时间:2025-11-07 16:29:01浏览:650

本文介绍一个基于PHP fsockopen函数实现的POP3协议操作类。该类封装了连接服务器、用户登录、获取邮件列表及内容等核心功能,支持STAT、UIDL、LIST、RETR、TOP和DELE等标准命令。代码参考RFC 2449规范,旨在通过实际编码练习掌握Socket网络通信机制。

本文目录展开

PHP Socket POP3客户端类实现详解

在研读 POP3/SMTP 协议规范时,为了深入理解底层通信原理,尝试独立开发一个用于处理邮件交互的操作类。其核心逻辑主要依赖 PHP 的 fsockopen 函数进行数据流的写入与读取。该实现仅覆盖了最基础的功能模块,作为学习 Socket 网络编程的实战案例。开发过程中参考了 RFC 2449 文档以及国外开源 Web 邮件系统 Uebimiau 的部分代码片段,但坚持原创编写,未直接复制其完整逻辑。相关代码如下:

class SocketPOP3Client { var $resHandler = NULL; var $bolIsLogin = false; var $strRequest = ''; var $strResponse = ''; var $arrRequest = array(); var $arrResponse = array();

//--------------- // 基础操作 //---------------

//构造函数 function SocketPOP3Client($strLoginEmail, $strLoginPasswd, $strPopHost='', $intPort='') { $this->strEmail = trim(strtolower($strLoginEmail)); $this->strPasswd = trim($strLoginPasswd); $this->strHost = trim(strtolower($strPopHost));

if ($this->strEmail=='' || $this->strPasswd=='') { $this->setMessage('Email address or Passwd is empty', 1001); return false; } if (!PReg_match("/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/i", $this->strEmail)) { $this->setMessage('Email address invalid', 1002); return false; } if ($this->strHost=='') { $this->strHost = substr(strrchr($this->strEmail, "@"), 1); } if ($intPort!='') { $this->intPort = $intPort; } $this->connectHost(); } //连接服务器 function connectHost() { if ($this->bolDebug) { echo "Connection ".$this->strHost." ...\r\n"; } if (!$this->getIsConnect()) { if ($this->strHost=='' || $this->intPort=='') { $this->setMessage('POP3 host or Port is empty', 1003); return false; } $this->resHandler = @fsockopen($this->strHost, $this->intPort, &$this->intErrorNum, &$this->strMessage, $this->intConnSecond); if (!$this->resHandler) { $strErrMsg = 'Connection POP3 host: '.$this->strHost.' failed'; $intErrNum = 2001; $this->setMessage($strErrMsg, $intErrNum); return false; } $this->getLineResponse(); if (!$this->getRestIsSucceed()) { return false; } } return true; }

//关闭连接 function closeHost() { if ($this->resHandler) { fclose($this->resHandler); } return true; }

//发送指令 function sendCommand($strCommand) { if ($this->bolDebug) { if (!preg_match("/PASS/", $strCommand)) { echo "Send Command: ".$strCommand."\r\n"; } else { echo "Send Command: PASS ******\r\n"; }

} if (!$this->getIsConnect()) { return false; } if (trim($strCommand)=='') { $this->setMessage('Request command is empty', 1004); return false; } $this->strRequest = $strCommand."\r\n"; $this->arrRequest[] = $strCommand; fputs($this->resHandler, $this->strRequest); return true; }

//提取响应信息第一行 function getLineResponse() { if (!$this->getIsConnect()) { return false; } $this->strResponse = fgets($this->resHandler, $this->intBuffSize); $this->arrResponse[] = $this->strResponse;

return $this->strResponse; }

//提取若干响应信息,$intReturnType是返回值类型, 1为字符串, 2为数组 function getRespMessage($intReturnType) { if (!$this->getIsConnect()) { return false; } if ($intReturnType == 1) { $strAllResponse = ''; while(!feof($this->resHandler)) { $strLineResponse = $this->getLineResponse(); if (preg_match("/^\+OK/", $strLineResponse)) { continue; } if (trim($strLineResponse)=='.') { break; } $strAllResponse .= $strLineResponse; } return $strAllResponse; } else { $arrAllResponse = array(); while(!feof($this->resHandler)) { $strLineResponse = $this->getLineResponse(); if (preg_match("/^\+OK/", $strLineResponse)) { continue; } if (trim($strLineResponse)=='.') { break; } $arrAllResponse[] = $strLineResponse; } return $arrAllResponse; } }

//提取请求是否成功 function getRestIsSucceed($strRespMessage='') { if (trim($responseMessage)=='') { if ($this->strResponse=='') { $this->getLineResponse(); } $strRespMessage = $this->strResponse; } if (trim($strRespMessage)=='') { $this->setMessage('Response message is empty', 2003); return false; } if (!preg_match("/^\+OK/", $strRespMessage)) { $this->setMessage($strRespMessage, 2000); return false; } return true; }

//获取是否已连接 function getIsConnect() { if (!$this->resHandler) { $this->setMessage("Nonexistent availability connection handler", 2002); return false; } return true; }

//设置消息 function setMessage($strMessage, $intErrorNum) { if (trim($strMessage)=='' || $intErrorNum=='') { return false; } $this->strMessage = $strMessage; $this->intErrorNum = $intErrorNum; return true; }

//获取消息 function getMessage() { return $this->strMessage; }

//获取错误号 function getErrorNum() { return $this->intErrorNum; }

//获取请求信息 function getRequest() { return $this->strRequest; }

//获取响应信息 function getResponse() { return $this->strResponse; }

//--------------- // 邮件原子操作 //---------------

//登录邮箱 function popLogin() { if (!$this->getIsConnect()) { return false; } $this->sendCommand("USER ".$this->strEmail); $this->getLineResponse(); $bolUserRight = $this->getRestIsSucceed();

$this->sendCommand("PASS ".$this->strPasswd); $this->getLineResponse(); $bolPassRight = $this->getRestIsSucceed();

if (!$bolUserRight || !$bolPassRight) { $this->setMessage($this->strResponse, 2004); return false; } $this->bolIsLogin = true; return true; }

//退出登录 function popLogout() { if (!$this->getIsConnect() && $this->bolIsLogin) { return false; } $this->sendCommand("QUIT"); $this->getLineResponse(); if (!$this->getRestIsSucceed()) { return false; } return true; }

//获取是否在线 function getIsOnline() { if (!$this->getIsConnect() && $this->bolIsLogin) { return false; } $this->sendCommand("NOOP"); $this->getLineResponse(); if (!$this->getRestIsSucceed()) { return false; } return true; }

//获取邮件数量和字节数(返回数组) function getMailSum($intReturnType=2) { if (!$this->getIsConnect() && $this->bolIsLogin) { return false; } $this->sendCommand("STAT"); $strLineResponse = $this->getLineResponse(); if (!$this->getRestIsSucceed()) { return false; } if ($intReturnType==1) { return $this->strResponse; } else { $arrResponse = explode(" ", $this->strResponse); if (!is_array($arrResponse) || count($arrResponse)<=0) { $this->setMessage('STAT command response message is error', 2006); return false; } return array($arrResponse[1], $arrResponse[2]); } }

//获取指定邮件得session Id function getMailSessId($intMailId, $intReturnType=2) { if (!$this->getIsConnect() && $this->bolIsLogin) { return false; } if (!$intMailId = intval($intMailId)) { $this->setMessage('Mail message id invalid', 1005); return false; } $this->sendCommand("UIDL ". $intMailId); $this->getLineResponse(); if (!$this->getRestIsSucceed()) { return false; } if ($intReturnType == 1) { return $this->strResponse; } else { $arrResponse = explode(" ", $this->strResponse); if (!is_array($arrResponse) || count($arrResponse)<=0) { $this->setMessage('UIDL command response message is error', 2006); return false; } return array($arrResponse[1], $arrResponse[2]); } }

//取得某个邮件的大小 function getMailSize($intMailId, $intReturnType=2) { if (!$this->getIsConnect() && $this->bolIsLogin) { return false; } $this->sendCommand("LIST ".$intMailId); $this->getLineResponse(); if (!$this->getRestIsSucceed()) { return false; } if ($intReturnType == 1) { return $this->strResponse; } else { $arrMessage = explode(' ', $this->strResponse); return array($arrMessage[1], $arrMessage[2]); } }

//获取邮件基本列表数组 function getMailBaseList($intReturnType=2) { if (!$this->getIsConnect() && $this->bolIsLogin) { return false; } $this->sendCommand("LIST"); $this->getLineResponse(); if (!$this->getRestIsSucceed()) { return false; } return $this->getRespMessage($intReturnType); }

//获取指定邮件所有信息,intReturnType是返回值类型,1是字符串,2是数组 function getMailMessage($intMailId, $intReturnType=1) { if (!$this->getIsConnect() && $this->bolIsLogin) { return false; } if (!$intMailId = intval($intMailId)) { $this->setMessage('Mail message id invalid', 1005); return false; } $this->sendCommand("RETR ". $intMailId); $this->getLineResponse(); if (!$this->getRestIsSucceed()) { return false; } return $this->getRespMessage($intReturnType); }

//获取某邮件前指定行, $intReturnType 返回值类型,1是字符串,2是数组 function getMailTopMessage($intMailId, $intTopLines=10, $intReturnType=1) { if (!$this->getIsConnect() && $this->bolIsLogin) { return false; } if (!$intMailId=intval($intMailId) || !$intTopLines=int($intTopLines)) { $this->setMessage('Mail message id or Top lines number invalid', 1005); return false; } $this->sendCommand("TOP ". $intMailId ." ". $intTopLines); $this->getLineResponse(); if (!$this->getRestIsSucceed()) { return false; } return $this->getRespMessage($intReturnType); }

//删除邮件 function delMail($intMailId) { if (!$this->getIsConnect() && $this->bolIsLogin) { return false; } if (!$intMailId=intval($intMailId)) { $this->setMessage('Mail message id invalid', 1005); return false; } $this->sendCommand("DELE ".$intMailId); $this->getLineResponse(); if (!$this->getRestIsSucceed()) { return false; } return true; }

//重置被删除得邮件标记为未删除 function resetDeleMail() { if (!$this->getIsConnect() && $this->bolIsLogin) { return false; } $this->sendCommand("RSET"); $this->getLineResponse(); if (!$this->getRestIsSucceed()) { return false; } return true; }

//--------------- // 调试操作 //---------------

//输出对象信息 function printObject() { print_r($this); exit; }

//输出错误信息 function printError() { echo "[Error Msg] : $strMessage \n"; echo "[Error Num] : $intErrorNum \n"; exit; }

//输出主机信息 function printHost() { echo "[Host] : $this->strHost \n"; echo "[Port] : $this->intPort \n"; echo "[Email] : $this->strEmail \n"; echo "[Passwd] : ******** \n"; exit; }

//输出连接信息 function printConnect() { echo "[Connect] : $this->resHandler \n"; echo "[Request] : $this->strRequest \n"; echo "[Response] : $this->strResponse \n"; exit; } }

?> //测试代码 //例如:$o = SocketPOP3Client('邮箱地址', '密码', 'POP3服务器', 'POP3端口')

/* set_time_limit(0); $o = new SocketPOPClient('abc@126.com', '123456', 'pop.126.com', '110'); $o->popLogin(); print_r($o->getMailBaseList()); print_r($o->getMailSum(1)); print_r($o->getMailTopMessage(2, 2, 2)); $o->popLogout(); $o->closeHost(); $o->printObject(); */ ?>

上一篇
Laravel 5 Cookie 正确设置、获取与清除详解

在 Laravel 框架中操作 Cookie 时,开发者常因误解 Request 和 Response 机制导致读取值为 null。本文详细解析 Cookie 的正确添加(推荐 queue 方法)、服务端与客户端的获取方式以及清除逻辑,帮助开发人员避开网上流传的错误方案,确保数据准确交互。

下一篇
Laravel集成Redis:配置、调用与Windows环境安装排错

本文详解在Laravel框架中集成Redis的完整流程,涵盖通过Composer安装predis/predis包、修改config/database.php及.env配置文件。文章提供了从创建路由到编写控制器方法的代码示例,并重点解决了Windows环境下因未启动Redis服务导致的ConnectionException错误,附带详细的Windows版Redis下载与本地安装步骤。

相关文章

更多
PHP使用Socket模拟HTTP POST/GET请求示例

本文提供在PHP中通过底层Socket函数直接构造并发送HTTP请求的代码示例。该方法绕过内置库,手动组装HTTP头与Body,适用于需要精细控制协议交互或受限环境下的数据提交场景。

2025.12.08 1,000
详解Nginx服务器中的Socket切分

NGINX 1.9.1版本引入SO_REUSEPORT套接字选项,允许多个套接字监听同一IP和端口组合,由内核负载均衡传入连接。该机制通过减少工作进程间的互斥锁竞争来提升多核系统性能。基准测试显示,启用reuseport后每秒请求量提升至默认配置的两到三倍,延迟及标准差显著降低,但需注意其不适用于mail上下文。

2025.01.02 977
PHP调用Socket接口测试实例

本文介绍如何使用PHP向Java编写的Socket服务端发送请求并获取返回结果。通过传递请求方法和参数,实现跨语言的网络数据交互,适用于需要底层TCP/UDP通信的场景。

2025.05.15 925
Linux UDP Socket 编程:原理与 C 语言实现

UDP协议提供无连接的不可靠数据报传输服务,无需建立连接即可通过recvfrom和sendto函数通信。本文对比TCP的可靠流式传输,解析UDP套接字SOCK_DGRAM特性,并展示基于C语言的Server端与Client端完整代码范例,涵盖端口绑定、地址结构及文件传输逻辑。

2026.08.29 833
PHP端口嗅探器:指定网站与端口的HTTP请求检测

该PHP脚本通过fsockopen函数建立与服务器的网络连接,发送HEAD HTTP/1.0请求以探测指定网站和端口的连通性。程序接收用户输入的服务器地址和端口号,执行查询后返回连接状态及响应数据,适用于快速验证特定服务是否在线。

2026.09.01 799
PHP中Socket连接及读写数据超时问题分析

PHP的fsockopen()仅支持连接超时,缺乏C语言风格的读写超时设置。通过stream_set_blocking()启用阻塞模式,并利用stream_set_timeout()设定秒级超时后,结合stream_get_meta_data()检查timed_out字段,可在每次fwrite或fread操作后精准判断是否发生超时,从而避免程序因等待数据而挂起。

2026.10.01 788

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。