栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

PHP实现支持SSL连接的SMTP邮件发送类

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PHP实现支持SSL连接的SMTP邮件发送类

本文实例讲述了PHP实现支持SSL连接的SMTP邮件发送类。分享给大家供大家参考。具体如下:

该实例代码测试过了gmail和QQ邮箱的SMTP。具体代码如下:
复制代码 代码如下:
class MySendMail {
   
    protected $_userName;
   
    protected $_password;
   
    protected $_sendServer;
   
    protected $_port;
   
    protected $_from;
   
    protected $_to = array();
   
    protected $_cc = array();
   
    protected $_bcc = array();
   
    protected $_subject;
   
    protected $_body;
   
    protected $_attachment = array();
   
    protected $_socket;
   
    protected $_isSecurity;
   
    protected $_errorMessage;
   
    public function setServer($server, $username="", $password="", $port=25, $isSecurity=false) {
        $this->_sendServer = $server;
        $this->_port = $port;
        $this->_isSecurity = $isSecurity;
        $this->_userName = empty($username) ? "" : base64_encode($username);
        $this->_password = empty($password) ? "" : base64_encode($password);
        return true;
    }
   
    public function setFrom($from) {
        $this->_from = $from;
        return true;
    }
   
    public function setReceiver($to) {
        $this->_to[] = $to;
        return true;
    }
   
    public function setCc($cc) {
        $this->_cc[] = $cc;
        return true;
    }
   
    public function setBcc($bcc) {
        $this->_bcc[] = $bcc;
        return true;
    }
   
    public function addAttachment($file) {
        if(!file_exists($file)) {
            $this->_errorMessage = "file " . $file . " does not exist.";
            return false;
        }
        $this->_attachment[] = $file;
        return true;
    }
   
    public function setMail($subject, $body) {
        $this->_subject = base64_encode($subject);
        $this->_body = base64_encode($body);
        return true;
    }
   
    public function sendMail() {
        $command = $this->getCommand();
        $this->_isSecurity ? $this->socketSecurity() : $this->socket();
        foreach ($command as $value) {
            $result = $this->_isSecurity ? $this->sendCommandSecurity($value[0], $value[1]) : $this->sendCommand($value[0], $value[1]);
            if($result) {
                continue;
            }
            else{
                return false;
            }
        }
        //其实这里也没必要关闭,smtp命令:QUIT发出之后,服务器就关闭了连接,本地的socket资源会自动释放
        $this->_isSecurity ? $this->closeSecutity() : $this->close();
        return true;
    }
   
    public function error(){
        if(!isset($this->_errorMessage)) {
            $this->_errorMessage = "";
        }
        return $this->_errorMessage;
    }
   
    protected function getCommand() {
        $separator = "----=_Part_" . md5($this->_from . time()) . uniqid(); //分隔符
        $command = array(
                array("HELO sendmailrn", 250)
            );
        if(!empty($this->_userName)){
            $command[] = array("AUTH LOGINrn", 334);
            $command[] = array($this->_userName . "rn", 334);
            $command[] = array($this->_password . "rn", 235);
        }
        //设置发件人
        $command[] = array("MAIL FROM: <" . $this->_from . ">rn", 250);
        $header = "FROM: <" . $this->_from . ">rn";
        //设置收件人
        if(!empty($this->_to)) {
            $count = count($this->_to);
            if($count == 1){
                $command[] = array("RCPT TO: <" . $this->_to[0] . ">rn", 250);
                $header .= "TO: <" . $this->_to[0] .">rn";
            }
            else{
                for($i=0; $i<$count; $i++){
                    $command[] = array("RCPT TO: <" . $this->_to[$i] . ">rn", 250);
                    if($i == 0){
                        $header .= "TO: <" . $this->_to[$i] .">";
                    }
                    elseif($i + 1 == $count){
                        $header .= ",<" . $this->_to[$i] .">rn";
                    }
                    else{
                        $header .= ",<" . $this->_to[$i] .">";
                    }
                }
            }
        }
        //设置抄送
        if(!empty($this->_cc)) {
            $count = count($this->_cc);
            if($count == 1){
                $command[] = array("RCPT TO: <" . $this->_cc[0] . ">rn", 250);
                $header .= "CC: <" . $this->_cc[0] .">rn";
            }
            else{
                for($i=0; $i<$count; $i++){
                    $command[] = array("RCPT TO: <" . $this->_cc[$i] . ">rn", 250);
                    if($i == 0){
                    $header .= "CC: <" . $this->_cc[$i] .">";
                    }
                    elseif($i + 1 == $count){
                        $header .= ",<" . $this->_cc[$i] .">rn";
                    }
                    else{
                        $header .= ",<" . $this->_cc[$i] .">";
                    }
                }
            }
        }
        //设置秘密抄送
        if(!empty($this->_bcc)) {
            $count = count($this->_bcc);
            if($count == 1) {
                $command[] = array("RCPT TO: <" . $this->_bcc[0] . ">rn", 250);
                $header .= "BCC: <" . $this->_bcc[0] .">rn";
            }
            else{
                for($i=0; $i<$count; $i++){
                    $command[] = array("RCPT TO: <" . $this->_bcc[$i] . ">rn", 250);
                    if($i == 0){
                    $header .= "BCC: <" . $this->_bcc[$i] .">";
                    }
                    elseif($i + 1 == $count){
                        $header .= ",<" . $this->_bcc[$i] .">rn";
                    }
                    else{
                        $header .= ",<" . $this->_bcc[$i] .">";
                    }
                }
            }
        }
        //主题
        $header .= "Subject: =?UTF-8?B?" . $this->_subject ."?=rn";
        if(isset($this->_attachment)) {
            //含有附件的邮件头需要声明成这个
            $header .= "Content-Type: multipart/mixed;rn";
        }
        elseif(false){
            //邮件体含有图片资源的,且包含的图片在邮件内部时声明成这个,如果是引用的远程图片,就不需要了
            $header .= "Content-Type: multipart/related;rn";
        }
        else{
            //html或者纯文本的邮件声明成这个
            $header .= "Content-Type: multipart/alternative;rn";
        }
        //邮件头分隔符
        $header .= "t" . 'boundary="' . $separator . '"';
        $header .= "rnMIME-Version: 1.0rn";
        //这里开始是邮件的body部分,body部分分成几段发送
        $header .= "rn--" . $separator . "rn";
        $header .= "Content-Type:text/html; charset=utf-8rn";
        $header .= "Content-Transfer-Encoding: base64rnrn";
        $header .= $this->_body . "rn";
        $header .= "--" . $separator . "rn";
        //加入附件
        if(!empty($this->_attachment)){
            $count = count($this->_attachment);
            for($i=0; $i<$count; $i++){
                $header .= "rn--" . $separator . "rn";
                $header .= "Content-Type: " . $this->getMIMEType($this->_attachment[$i]) . '; name="=?UTF-8?B?' . base64_encode( basename($this->_attachment[$i]) ) . '?="' . "rn";
                $header .= "Content-Transfer-Encoding: base64rn";
                $header .= 'Content-Disposition: attachment; filename="=?UTF-8?B?' . base64_encode( basename($this->_attachment[$i]) ) . '?="' . "rn";
                $header .= "rn";
                $header .= $this->readFile($this->_attachment[$i]);
                $header .= "rn--" . $separator . "rn";
            }
        }
        //结束邮件数据发送
        $header .= "rn.rn";
 
        $command[] = array("DATArn", 354);
        $command[] = array($header, 250);
        $command[] = array("QUITrn", 221);
        return $command;
    }
   
    protected function sendCommand($command, $code) {
        echo 'Send command:' . $command . ',expected code:' . $code . '
';
        //发送命令给服务器
        try{
            if(socket_write($this->_socket, $command, strlen($command))){
                //当邮件内容分多次发送时,没有$code,服务器没有返回
                if(empty($code))  {
                    return true;
                }
                //读取服务器返回
                $data = trim(socket_read($this->_socket, 1024));
                echo 'response:' . $data . '

';
                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();
        }
    }
   
    protected function sendCommandSecurity($command, $code) {
        echo 'Send command:' . $command . ',expected code:' . $code . '
';
        try {
            if(fwrite($this->_socket, $command)){
                //当邮件内容分多次发送时,没有$code,服务器没有返回
                if(empty($code))  {
                    return true;
                }
                //读取服务器返回
                $data = trim(fread($this->_socket, 1024));
                echo 'response:' . $data . '

';
                if($data) {
                    $pattern = "/^".$code."+?/";
                    if(preg_match($pattern, $data)) {
                        return true;
                    }
                    else{
                        $this->_errorMessage = "Error:" . $data . "|**| command:";
                        return false;
                    }
                }
                else{
                    return false;
                }
            }
            else{
                $this->_errorMessage = "Error: " . $command . " send failed";
                return false;
            }
        }catch(Exception $e) {
            $this->_errorMessage = "Error:" . $e->getMessage();
        }
    }
   
    protected function readFile($file) {
        if(file_exists($file)) {
            $file_obj = file_get_contents($file);
            return base64_encode($file_obj);
        }
        else {
            $this->_errorMessage = "file " . $file . " dose not exist";
            return false;
        }
    }
   
    protected function getMIMEType($file) {
        if(file_exists($file)) {
            $mime = mime_content_type($file);
           
            return $mime;
        }
        else {
            return false;
        }
    }
   
    protected function socket() {
        //创建socket资源
        $this->_socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
        if(!$this->_socket) {
            $this->_errorMessage = socket_strerror(socket_last_error());
            return false;
        }
        socket_set_block($this->_socket);//设置阻塞模式
        //连接服务器
        if(!socket_connect($this->_socket, $this->_sendServer, $this->_port)) {
            $this->_errorMessage = socket_strerror(socket_last_error());
            return false;
        }
        $str = socket_read($this->_socket, 1024);
        if(!preg_match("/220+?/", $str)){
            $this->_errorMessage = $str;
            return false;
        }
        return true;
    }
   
    protected function socketSecurity() {
        $remoteAddr = "tcp://" . $this->_sendServer . ":" . $this->_port;
        $this->_socket = stream_socket_client($remoteAddr, $errno, $errstr, 30);
        if(!$this->_socket){
            $this->_errorMessage = $errstr;
            return false;
        }
        //设置加密连接,默认是ssl,如果需要tls连接,可以查看php手册stream_socket_enable_crypto函数的解释
        stream_socket_enable_crypto($this->_socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
        stream_set_blocking($this->_socket, 1); //设置阻塞模式
        $str = fread($this->_socket, 1024);
        if(!preg_match("/220+?/", $str)){
            $this->_errorMessage = $str;
            return false;
        }
        return true;
    }
   
    protected 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;
    }
   
    protected function closeSecutity() {
        if(isset($this->_socket) && is_object($this->_socket)) {
            stream_socket_shutdown($this->_socket, STREAM_SHUT_WR);
            return true;
        }
        $this->_errorMessage = "No resource can to be close";
        return false;
    }
}

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/46124.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号