欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php基于socket实现SMTP发送邮件的方法

程序员文章站 2023-02-17 08:26:22
本文实例讲述了php基于socket实现smtp发送邮件的方法。分享给大家供大家参考。具体分析如下: php采用socket通过smtp发送邮件。 用的是php的php...

本文实例讲述了php基于socket实现smtp发送邮件的方法。分享给大家供大家参考。具体分析如下:

php采用socket通过smtp发送邮件。
用的是php的php-sockets扩展,可以发送纯文本和html格式的邮件。代码如下:

复制代码 代码如下:

<?php
/**
* 邮件发送类
* 支持发送纯文本邮件和html格式的邮件
* @example
* $config = array(
*       "from" => "*****",
*       "to" => "***",
*       "subject" => "test",
*       "body" => "<b>test</b>",
*       "username" => "***",
*       "password" => "****",
*       "ishtml" => true
*   );
*
* $mail = new mysendmail();
*
* $mail->setserver("smtp.126.com");
*
* $mail->setmailinfo($config);
* if(!$mail->sendmail()) {
*   echo $mail->error();
*   return 1;
* }
*/
class mysendmail {
    /**
    * @var 邮件传输代理用户名
    * @access private
    */
    private $_username;
    /**
    * @var 邮件传输代理密码
    * @access private
    */
    private $_password;
    /**
    * @var 邮件传输代理服务器地址
    * @access protected
    */
    protected $_sendserver;
    /**
    * @var 邮件传输代理服务器端口
    * @access protected
    */
    protected $_port=25;
    /**
    * @var 发件人
    * @access protected
    */
    protected $_from;
    /**
    * @var 收件人
    * @access protected
    */
    protected $_to;
    /**
    * @var 主题
    * @access protected
    */
    protected $_subject;
    /**
    * @var 邮件正文
    * @access protected
    */
    protected $_body;
    /**
    * @var 是否是html格式的邮件
    * @access protected
    */
    protected $_ishtml=false;
    /**
    * @var socket资源
    * @access protected
    */
    protected $_socket;
    /**
    * @var 错误信息
    * @access protected
    */
    protected $_errormessage;
    public function __construct($from="", $to="", $subject="", $body="", $server="", $username="", $password="",$ishtml="", $port="") {
        if(!empty($from)){
            $this->_from = $from;
        }
        if(!empty($to)){
            $this->_to = $to;
        }
        if(!empty($subject)){
            $this->_subject = $subject;
        }
        if(!empty($body)){
            $this->_body = $body;
        }
        if(!empty($ishtml)){
            $this->_ishtml = $ishtml;
        }
        if(!empty($server)){
            $this->_sendserver = $server;
        }
        if(!empty($port)){
            $this->_port = $port;
        }
        if(!empty($username)){
            $this->_username = $username;
        }
        if(!empty($password)){
            $this->_password = $password;
        }
    }
    /**
    * 设置邮件传输代理
    * @param string $server 代理服务器的ip或者域名
    * @param int $port 代理服务器的端口,smtp默认25号端口
    * @param int $localport 本地端口
    * @return boolean
    */
    public function setserver($server, $port=25) {
        if(!isset($server) || empty($server) || !is_string($server)) {
            $this->_errormessage = "first one is an invalid parameter";
            return false;
        }
        if(!is_numeric($port)){
            $this->_errormessage = "first two is an invalid parameter";
            return false;
        }
        $this->_sendserver = $server;
        $this->_port = $port;
        return true;
    }
    /**
    * 设置邮件
    * @access public
    * @param array $config 邮件配置信息
    * 包含邮件发送人、接收人、主题、内容、邮件传输代理的验证信息
    * @return boolean
    */
    public function setmailinfo($config) {
        if(!is_array($config) || count($config) < 6){
            $this->_errormessage = "parameters are required";
            return false;
        }
        $this->_from = $config['from'];
        $this->_to = $config['to'];
        $this->_subject = $config['subject'];
        $this->_body = $config['body'];
        $this->_username = $config['username'];
        $this->_password = $config['password'];
        if(isset($config['ishtml'])){
            $this->_ishtml = $config['ishtml'];
        }
        return true;
    }
    /**
    * 发送邮件
    * @access public
    * @return boolean
    */
    public function sendmail() {
        $command = $this->getcommand();
        $this->socket();
        foreach ($command as $value) {
            if($this->sendcommand($value[0], $value[1])) {
                continue;
            }
            else{
                return false;
            }
        }
        $this->close(); //其实这里也没必要关闭,smtp命令:quit发出之后,服务器就关闭了连接,本地的socket资源会自动释放
        echo 'mail ok!';
        return true;
    }
    /**
    * 返回错误信息
    * @return string
    */
    public function error(){
        if(!isset($this->_errormessage)) {
            $this->_errormessage = "";
        }
        return $this->_errormessage;
    }
    /**
    * 返回mail命令
    * @access protected
    * @return array
    */
    protected function getcommand() {
        if($this->_ishtml) {
            $mail = "mime-version:1.0\r\n";
            $mail .= "content-type:text/html;charset=utf-8\r\n";
            $mail .= "from:test<" . $this->_from . ">\r\n";
            $mail .= "to:<" . $this->_to . ">\r\n";
            $mail .= "subject:" . $this->_subject ."\r\n\r\n";
            $mail .= $this->_body . "\r\n.\r\n";
        }
        else{
            $mail = "from:test<" . $this->_from . ">\r\n";
            $mail .= "to:<" . $this->_to . ">\r\n";
            $mail .= "subject:" . $this->_subject ."\r\n\r\n";
            $mail .= $this->_body . "\r\n.\r\n";
        }
        $command = array(
                array("helo sendmail\r\n", 250),
                array("auth login\r\n", 334),
                array(base64_encode($this->_username) . "\r\n", 334),
                array(base64_encode($this->_password) . "\r\n", 235),
                array("mail from:<" . $this->_from . ">\r\n", 250),
                array("rcpt to:<" . $this->_to . ">\r\n", 250),
                array("data\r\n", 354),
                array($mail, 250),
                array("quit\r\n", 221)
        );
        return $command;
    }
    /**
    * @access protected
    * @param string $command 发送到服务器的smtp命令
    * @param int $code 期望服务器返回的响应吗
    * @param boolean
    */
    protected function sendcommand($command, $code) {
        echo 'send command:' . $command . ',expected code:' . $code . '<br />';
        //发送命令给服务器
        try{
            if(socket_write($this->_socket, $command, strlen($command))){
                //读取服务器返回
                $data = trim(socket_read($this->_socket, 1024));
                echo 'response:' . $data . '<br /><br />';
                if($data) {
                    $pattern = "/^".$code."/";
                    if(preg_match($pattern, $data)) {
                        return true;
                    }
                    else{
                        $this->_errormessage = "error:" . $data . "|**| command:";
                        return false;
                    }
                }
                else{
                    $this->_errormessage = "error:" . socket_strerror(socket_last_error());
                    return false;
                }
            }
            else{
                $this->_errormessage = "error:" . socket_strerror(socket_last_error());
                return false;
            }
        }catch(exception $e) {
            $this->_errormessage = "error:" . $e->getmessage();
        }
    }
    /**
    * 建立到服务器的网络连接
    * @access private
    * @return boolean
    */
    private function socket() {
        if(!function_exists("socket_create")) {
            $this->_errormessage = "extension php-sockets must be enabled";
            return false;
        }
        //创建socket资源
        $this->_socket = socket_create(af_inet, sock_stream, getprotobyname('tcp'));
        if(!$this->_socket) {
            $this->_errormessage = socket_strerror(socket_last_error());
            return false;
        }
        //连接服务器
        if(!socket_connect($this->_socket, $this->_sendserver, $this->_port)) {
            $this->_errormessage = socket_strerror(socket_last_error());
            return false;
        }
        socket_read($this->_socket, 1024);
        return true;
    }
    /**
    * 关闭socket
    * @access private
    * @return boolean
    */
    private function close() {
        if(isset($this->_socket) && is_object($this->_socket)) {
            $this->_socket->close();
            return true;
        }
        $this->_errormessage = "no resource can to be close";
        return false;
    }
}
/**************************** test ***********************************/
$config = array(
        "from" => "xxxxx",
        "to" => "xxxxx",
        "subject" => "test",
        "body" => "<b>test</b>",
        "username" => "xxxxx",
        "password" => "******",
        //"ishtml" => true
    );
$mail = new mysendmail();
$mail->setserver("smtp.126.com");
$mail->setmailinfo($config);
if(!$mail->sendmail()) {
    echo $mail->error();
    return 1;
}

希望本文所述对大家的php程序设计有所帮助。