php socket 基础型发邮件类
php socket 基础型发邮件类 , fsocketopen pfsocketopen 一般空间服务商都会禁用。
此时可自已动手 利用SMTP协议 用socket_create,socket_connect 与邮件服务器进行连接、通信。
关于smtp 可去 搜索 了解一个 发送邮件 的格式 。
在写此代码时注意到的一个问题,跟邮件服务发命令时,不要使用 单引号 如 ' 要使用双引号 "
不然邮件服务器 不识别命令。比如命令 "EHLO HELO\r\n",因为每条命令 都要加 \r\n 如果用 单引号包含 \r\n会被当做 字符发出去 而不会 形成 回车符 换行符。
此类已经 集成到phpx(自己写的PHP轻型框架中)框架中,
<?php
final class mail{
private $from=null,$pass=null,$to=null;
private $smtp=null,$port=null;
private $socket=null;
private $data=null;
public function __construct($array=null){
$this->smtp=$array[0];
$this->port=$array[1];
$this->from=$array[2];
$this->pass=$array[3];
$this->to=$array[4];
}
public function send($header=null,$body=null){
$this->socket=socket_create(AF_INET,SOCK_STREAM,getprotobyname('tcp'));
if(!$this->socket){
exit('创建socket失败');
}
if(socket_connect($this->socket,$this->smtp,$this->port)){
$this->debug('服务器连接应答:'.socket_strerror(socket_last_error()));
}
else{
exit('socket连接失败');
}
$this->data="EHLO HELO\\r\\n";
$this->do_send();
$this->data="AUTH LOGIN\\r\\n";
$this->do_send();
$this->data=base64_encode($this->from)."\\r\\n";
$this->do_send();
$this->data=base64_encode($this->pass)."\\r\\n";
$this->do_send();
$this->data="MAIL FROM:<".$this->from.">\\r\\n";
$this->do_send();
$this->data="RCPT TO:<".$this->to.">\\r\\n";
$this->do_send();
$this->data="DATA\\r\\n";
$this->do_send();
$this->data="From:代码片段<".$this->from.">\\r\\n";
$this->data.="Subject:".$header."\\r\\n\\r\\n";
$this->data.=$body."\\r\\n.\\r\\n";
$this->do_send();
$this->data="QUIT\\r\\n";
$this->do_send();
socket_close($this->socket);
}
public function do_send(){
socket_write($this->socket,$this->data,strlen($this->data));
$this->debug('客户端发送:'.$this->data);
$this->debug('服务器应答:'.socket_read($this->socket,1024)).'<br>';
}
public function debug($args=null){
echo $args.'<br>';
}
}
?>
//该片段来自于http://outofmemory.cn
- 上一篇:php抓取百度贴吧图片
- 下一篇:php 由页面倾斜扩展的页面晃动






