class smtp_mail
{
var $lastmessage; //记录最后返回的响应信息
var $lastact; //最后的动作,字符串形式
var $welcome; //用在helo后面,欢迎用户
var $debug; //是否显示调试信息
var $smtp; //smtp服务器
var $port; //smtp端口号
var $fp; //socket句柄
function smtp_mail($smtp, $welcome="", $debug=false)
{
if(empty($smtp)) die("smtp cannt be null!");
$this->smtp=$smtp;
if(empty($welcome))
{
$this->welcome=gethostbyaddr("localhost");
}
else
$this->welcome=$welcome;
$this->debug=$debug;
$this->lastmessage="";
$this->lastact="";
$this->port="25";
}
function show_debug($message, $inout)
{
$b = false;
if ($this->debug)
{
if($inout=="in") //响应信息
{
$m='<< ';
$b = true;
}
else //请求指令
$m='>> ';
if(!ereg(" $", $message))
$message .= "";
$message=nl2br($message);
if($b)
echo "${m}${message}";
else
echo "${m}${message}";
}
}
function do_command($command, $code)
{
$this->lastact=$command;
$this->show_debug($this->lastact, "out");
fputs ( $this->fp, $this->lastact );
$this->lastmessage = fgets ( $this->fp, 512 );
$this->show_debug($this->lastmessage, "in");
if(!ereg("^$code", $this->lastmessage))
{
return false;
}
else
return true;
}
function send($from,$to,$subject,$message)
{
$this->show_debug("connect to smtp server : ".$this->smtp." ", "out");
$this->fp = fsockopen ( $this->smtp, $this->port );
if ( $this->fp )
{
set_socket_blocking( $this->fp, true );
$this->lastmessage=fgets($this->fp,512);
$this->show_debug($this->lastmessage, "in");
if (! ereg ( "^220", $this->lastmessage ) )
{
return false;
}
else
{
$this->lastact="helo " . $this->welcome . " ";
if(!$this->do_command($this->lastact, "250"))
{
fclose($this->fp);
return false;
}
$this->lastact="mail from:<$from>". " ";
if(!$this->do_command($this->lastact, "250"))
{
fclose($this->fp);
return false;
}
$this->lastact="rcpt to:<$to>" . " ";
if(!$this->do_command($this->lastact, "250"))
{
fclose($this->fp);
return false;
}
$this->lastact="data "; //发送正文
if(!$this->do_command($this->lastact, "354"))
{
fclose($this->fp);
return false;
}
$head="subject: $subject "; //处理subject
if(!empty($subject) && !ereg($head, $message))
{
$message = $head.$message;
}
$head="from: $from "; //处理from
if(!empty($from) && !ereg($head, $message))
{
$message = $head.$message;
}
$head="to: $to "; //处理to
if(!empty($to) && !ereg($head, $message))
{
$message = $head.$message;
}
if(!ereg(" . ", $message)) //加上结束串
$message .= " . ";
$this->show_debug($message, "out");
fputs($this->fp, $message);
$this->lastact="quit ";
if(!$this->do_command($this->lastact, "250"))
{
fclose($this->fp);
return false;
}
}
return true;
}
else
{
$this->show_debug("connect failed!", "in");
return false;
}
}
}
|