zoukankan      html  css  js  c++  java
  • 邮箱发送

    一个邮箱类(网上找的),重新做了一些备注和注释

    <?php
    
    class smtp
    {
        /* Public Variables */
        public $smtp_port; //端口
        public $time_out;  //超时等待时间
        public $host_name;  //发件人的邮件服务器地址
        public $log_file;  //日志文件
        public $relay_host; //SMTP服务器
        public $debug; //是否开启debug true开启
        public $auth;  //是否使用身份验证 true是
        public $user;  //邮件用户名
        public $pass;  //邮件密码
    
        /* Private Variables */
        private $sock; //连接网络请求内容
    
        /* Constractor */
        function smtp($relay_host = "", $smtp_port = 25, $auth = false, $user, $pass)
        {
            $this->debug = FALSE;
            $this->smtp_port = $smtp_port;
            $this->relay_host = $relay_host;
            $this->time_out = 30; //is used in fsockopen() 打开一个网络请求
            #
            $this->auth = $auth;//auth
            $this->user = $user;
            $this->pass = $pass;
            #
            $this->host_name = "localhost"; //is used in HELO command 用于Helo命令
            $this->log_file = "";
    
            $this->sock = FALSE;
        }
    
        /* Main Function */
        /**
         * 发送邮箱
         * @param string $to 收件人
         * @param string $from 发件人
         * @param string $from_title 发件人名称显示
         * @param string $subject 邮件主题
         * @param string $body 邮件内容
         * @param string $mailtype 邮件格式(HTML/TXT),TXT为文本邮件
         * @param string $cc 抄送地址. 多个地址使用','分隔
         * @param string $bcc 密送地址. 多个地址使用','分隔
         * @param string $additional_headers 附加标题
        */
        function sendmail($to, $from, $from_title,$subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
        {
            $mail_from = $this->get_address($this->strip_comment($from));
            $body = preg_replace("/(^|(
    ))(\.)/", "\1.\3", $body);
            $header = "MIME-Version:1.0
    ";
            if ($mailtype == "HTML") {
                $header .= "Content-Type:text/html
    ";
            }
            $header .= "To: " . $to . "
    ";
            //抄送地址. 多个地址使用';'分隔
            if ($cc != "") {
                $header .= "Cc: " . $cc . "
    ";
            }
            $header .= "From: $from_title<" . $from . ">
    ";
            $header .= "Subject: " . $subject . "
    ";
            $header .= $additional_headers;
            $header .= "Date: " . date("r") . "
    ";
            $header .= "X-Mailer:By Redhat (PHP/" . phpversion() . ")
    ";
            //list 把数组中的值赋给一些变量:
            list($msec, $sec) = explode(" ", microtime());
            $header .= "Message-ID: <" . date("YmdHis", $sec) . "." . ($msec * 1000000) . "." . $mail_from . ">
    ";
            $TO = explode(",", $this->strip_comment($to));
            if ($cc != "") {
                $TO = array_merge($TO, explode(",", $this->strip_comment($cc)));
            }
            //密送地址. 多个地址使用';'分隔
            if ($bcc != "") {
                $TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));
            }
    
            $sent = TRUE;
            //$TO 收件人 抄送 密送 一维数组
            foreach ($TO as $rcpt_to) {
                //$rcpt 收件人
                $rcpt_to = $this->get_address($rcpt_to);
                if (!$this->smtp_sockopen($rcpt_to)) {
                    $this->log_write("Error: Cannot send email to " . $rcpt_to . "
    ");
                    $sent = FALSE;
                    continue;
                }
    //            var_dump($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body));die;
                if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) {
                    $this->log_write("E-mail has been sent to <" . $rcpt_to . ">
    ");
                } else {
                    $this->log_write("Error: Cannot send email to <" . $rcpt_to . ">
    ");
                    $sent = FALSE;
                }
                fclose($this->sock);
                $this->log_write("Disconnected from remote host
    ");
            }
    //        echo "<br>";
    //        echo $header;
            return $sent;
        }
    
        /* Private Functions */
    
        /**
         * 执行发送
         * @param string $helo 服务器地址
         * @param string $from 发件人
         * @param string $to 收件人
         * @param string $header header头信息
         * @param string $body 邮件内容
        */
        function smtp_send($helo, $from, $to, $header, $body = "")
        {
            // HELO命令提供域名信息
            //执行HELO命令 拼接 提供域名信息
            if (!$this->smtp_putcmd("HELO", $helo)) {
                return $this->smtp_error("sending HELO command");
            }
            #auth
            if ($this->auth) {
    //            print_r($this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user)));die;
                if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
                    return $this->smtp_error("sending HELO command");
                }
                if (!$this->smtp_putcmd("", base64_encode($this->pass))) {
                    return $this->smtp_error("sending HELO command");
                }
            }
            #
            if (!$this->smtp_putcmd("MAIL", "FROM:<" . $from . ">")) {
    
                return $this->smtp_error("sending MAIL FROM command");
            }
    
            if (!$this->smtp_putcmd("RCPT", "TO:<" . $to . ">")) {
                return $this->smtp_error("sending RCPT TO command");
            }
    
            if (!$this->smtp_putcmd("DATA")) {
                return $this->smtp_error("sending DATA command");
            }
    
            if (!$this->smtp_message($header, $body)) {
                return $this->smtp_error("sending message");
            }
    
            if (!$this->smtp_eom()) {
                return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]");
            }
    
            if (!$this->smtp_putcmd("QUIT")) {
                return $this->smtp_error("sending QUIT command");
            }
            return TRUE;
        }
    
        function smtp_sockopen($address)
        {
            if ($this->relay_host == "") {
                return $this->smtp_sockopen_mx($address);
            } else {
                return $this->smtp_sockopen_relay();
            }
        }
    
        function smtp_sockopen_relay()
        {
            $this->log_write("Trying to " . $this->relay_host . ":" . $this->smtp_port . "
    ");
            //打开一个网络连接或者一个Unix套接字连接 参数 主机地址 端口 错误信息 错误信息以字符串返回 连接时限
            $this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);
            //连接失败
            if (!($this->sock && $this->smtp_ok())) {
                $this->log_write("Error: Cannot connenct to relay host " . $this->relay_host . "
    ");
                $this->log_write("Error: " . $errstr . " (" . $errno . ")
    ");
                return FALSE;
            }
            $this->log_write("Connected to relay host " . $this->relay_host . "
    ");
            return TRUE;
        }
    
        function smtp_sockopen_mx($address)
        {
            //取替换截取 163.com
            $domain = preg_replace("/^.+@([^@]+)$/", "\1", $address);
            //获取互联网主机名对应的 MX DNS记录
            if (!@getmxrr($domain, $MXHOSTS)) {
                $this->log_write("Error: Cannot resolve MX "" . $domain . ""
    ");
                return FALSE;
            }
            foreach ($MXHOSTS as $host) {
                $this->log_write("Trying to " . $host . ":" . $this->smtp_port . "
    ");
                $this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
                if (!($this->sock && $this->smtp_ok())) {
                    $this->log_write("Warning: Cannot connect to mx host " . $host . "
    ");
                    $this->log_write("Error: " . $errstr . " (" . $errno . ")
    ");
                    continue;
                }
                $this->log_write("Connected to mx host " . $host . "
    ");
                return TRUE;
            }
            $this->log_write("Error: Cannot connect to any mx hosts (" . implode(", ", $MXHOSTS) . ")
    ");
            return FALSE;
        }
    
        function smtp_message($header, $body)
        {
            fputs($this->sock, $header . "
    " . $body);
            $this->smtp_debug("> " . str_replace("
    ", "
    " . "> ", $header . "
    > " . $body . "
    > "));
    
            return TRUE;
        }
    
        function smtp_eom()
        {
            fputs($this->sock, "
    .
    ");
            $this->smtp_debug(". [EOM]
    ");
    
            return $this->smtp_ok();
        }
    
        /**
         * 是否发送成功
         *
        */
        function smtp_ok()
        {
            //从文件中取出一行
            $response = str_replace("
    ", "", fgets($this->sock, 512));
            $this->smtp_debug($response . "
    ");
    //        print_r($response);die;
            if (!preg_match("/^[23]/", $response)) {
                //写入文件
                fputs($this->sock, "QUIT
    ");
                fgets($this->sock, 512);
                $this->log_write("Error: Remote host returned "" . $response . ""
    ");
                return FALSE;
            }
            return TRUE;
        }
    
        /**
         *  拼接 信息
         * @param string $cmd HELO/AUTH等
         * @param string $arg
        */
        function smtp_putcmd($cmd, $arg = "")
        {
            if ($arg != "") {
                if ($cmd == "") $cmd = $arg;
                else $cmd = $cmd . " " . $arg;
            }
    //        print_r($this->sock);die;
            fputs($this->sock, $cmd . "
    ");
            $this->smtp_debug("> " . $cmd . "
    ");
    
            return $this->smtp_ok();
        }
    
        /**
         * 错误信息
        */
        function smtp_error($string)
        {
            $this->log_write("Error: Error occurred while " . $string . ".
    ");
            return FALSE;
    //        return "Error: Error occurred while " . $string . ".
    ";
        }
    
        /**
         * 写入日志
         * @param string $message 写入日志信息
        */
        function log_write($message)
        {
            $this->smtp_debug($message);
    
            if ($this->log_file == "") {
                return TRUE;
            }
    
            //get_current_user取当前 PHP 脚本所有者名称  getmypid 获取 PHP 进程的 ID
            $message = date("M d H:i:s ") . get_current_user() . "[" . getmypid() . "]: " . $message;
            if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {
                $this->smtp_debug("Warning: Cannot open log file "" . $this->log_file . ""
    ");
                return FALSE;
            }
            // 函数锁定或释放文件。
            flock($fp, LOCK_EX);
            fputs($fp, $message);
            fclose($fp);
    
            return TRUE;
        }
    
        function strip_comment($address)
        {
            $comment = "/\([^()]*\)/";
            //正则匹配
            while (preg_match($comment, $address)) {
                $address = preg_replace($comment, "", $address);
            }
    
            return $address;
        }
    
        function get_address($address)
        {
            //正则搜索替换
            $address = preg_replace("/([ 	
    ])+/", "", $address);
            $address = preg_replace("/^.*<(.+)>.*$/", "\1", $address);
    
            return $address;
        }
    
        /**
         * 输出错误信息
         * @param string $message 错误信息
        */
        function smtp_debug($message)
        {
            if ($this->debug) {
                echo $message . "<br>";
            }
        }
    
        function get_attach_type($image_tag)
        { //
    
            $filedata = array();
    
            $img_file_con = fopen($image_tag, "r");
            unset($image_data);
            while ($tem_buffer = AddSlashes(fread($img_file_con, filesize($image_tag))))
                $image_data = $tem_buffer;
            fclose($img_file_con);
    
            $filedata['context'] = $image_data;
            $filedata['filename'] = basename($image_tag);
            $extension = substr($image_tag, strrpos($image_tag, "."), strlen($image_tag) - strrpos($image_tag, "."));
            switch ($extension) {
                case ".gif":
                    $filedata['type'] = "image/gif";
                    break;
                case ".gz":
                    $filedata['type'] = "application/x-gzip";
                    break;
                case ".htm":
                    $filedata['type'] = "text/html";
                    break;
                case ".html":
                    $filedata['type'] = "text/html";
                    break;
                case ".jpg":
                    $filedata['type'] = "image/jpeg";
                    break;
                case ".tar":
                    $filedata['type'] = "application/x-tar";
                    break;
                case ".txt":
                    $filedata['type'] = "text/plain";
                    break;
                case ".zip":
                    $filedata['type'] = "application/zip";
                    break;
                default:
                    $filedata['type'] = "application/octet-stream";
                    break;
            }
            return $filedata;
        }
    
    } // end class
    ?>

    发送邮箱:

    /**
    * 发送邮箱
    * @param string $smtpemailto 要发送给谁
    */
    function email($smtpemailto){
    require_once('smtp.class.php');
    $smtpserver = "smtp.qq.com";//发送者的邮箱类型服务 这里以QQ邮箱为例
    $smtpserverport = 25;//端口号
    $smtpusermail = "";//SMTP服务器的用户邮箱
    $smtpuser = "";//SMTP服务器的用户帐号
    $smtppass = "";//SMTP服务器的用户密码 不是自己登陆密码
    $from_title = '';
    $mailsubject = "";//邮件主题
    $mailbody = "";//邮件内容
    $mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件
    $smtp = new smtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
    // $smtp->debug = true;//是否显示发送的调试信息
    $ok = $smtp->sendmail($smtpemailto, $smtpusermail, $from_title ,$mailsubject, $mailbody, $mailtype, $cc = "", $bcc = "", $additional_headers = "");
    }

    以上就是这次的全部内容!

  • 相关阅读:
    获得插入记录标识号, 鼠标移到DataGrid的行更改颜色(转)
    ESRI ArcGIS 9.0系列软件报价(转)
    世界电子地图
    Microsoft’s.NET MicroFramework初接触
    MapServer初体验成功
    MapScript C# Tutorial Programming MapServer in the ASP .NET Framework(转)
    WPF 中的Width 与 ActualWidth
    可空值类型
    面试时遇到上机编程题
    checked、unchecked
  • 原文地址:https://www.cnblogs.com/jingxiaoniu/p/9559307.html
Copyright © 2011-2022 走看看