zoukankan      html  css  js  c++  java
  • PHP发送电子邮件

    1、导入文件,如本案例把Stmp.class.php放到CommonCommon目录下,代码很多,直接复制就行!

      1 <?php
      2 namespace CommonCommon;
      3 
      4 class Smtp
      5 {
      6     /* Public Variables */
      7     var $smtp_port;
      8     var $time_out;
      9     var $host_name;
     10     var $log_file;
     11     var $relay_host;
     12     var $debug;
     13     var $auth;
     14     var $user;
     15     var $pass;
     16 
     17     /* Private Variables */ 
     18     var $sock;
     19 
     20     /* Constractor */
     21 
     22     function __construct($relay_host = "", $smtp_port = 25,$auth = false,$user,$pass)
     23     {
     24         $this->debug = FALSE;
     25         $this->smtp_port = $smtp_port;
     26         $this->relay_host = $relay_host;
     27         $this->time_out = 30; //is used in fsockopen() 
     28         
     29         #
     30 
     31         $this->auth = $auth;//auth
     32         $this->user = $user;
     33         $this->pass = $pass;
     34         
     35         #
     36 
     37         $this->host_name = "localhost"; //is used in HELO command 
     38         $this->log_file = "";
     39         $this->sock = FALSE;
     40     }
     41     /* Main Function */
     42 
     43     function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
     44     {
     45         $mail_from = $this->get_address($this->strip_comment($from));
     46         $body = ereg_replace("(^|(
    ))(.)", "1.3", $body);
     47         $header = "MIME-Version:1.0
    ";
     48 
     49         if($mailtype=="HTML"){
     50             $header .= "Content-Type:text/html
    ";
     51         }
     52 
     53         $header .= "To: ".$to."
    ";
     54 
     55         if ($cc != "") {
     56             $header .= "Cc: ".$cc."
    ";
     57         }
     58 
     59         $header .= "From: 在线图书系统<".$from.">
    ";
     60         $header .= "Subject: ".$subject."
    ";
     61         $header .= $additional_headers;
     62         $header .= "Date: ".date("r")."
    ";
     63         $header .= "X-Mailer:By Redhat (PHP/".phpversion().")
    ";
     64         $utfheader=iconv("UTF-8","GB2312",$header);
     65         list($msec, $sec) = explode(" ", microtime());
     66 
     67         $header .= "Message-ID: <".date("YmdHis", $sec).".".($msec*1000000).".".$mail_from.">
    ";
     68 
     69         $TO = explode(",", $this->strip_comment($to));
     70 
     71         if ($cc != "") {
     72             $TO = array_merge($TO, explode(",", $this->strip_comment($cc)));
     73         }
     74 
     75 
     76         if ($bcc != "") {
     77             $TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));
     78         }
     79 
     80         $sent = TRUE;
     81 
     82         foreach ($TO as $rcpt_to) {
     83             $rcpt_to = $this->get_address($rcpt_to);
     84             
     85             if (!$this->smtp_sockopen($rcpt_to)) {
     86                 $this->log_write("Error: Cannot send email to ".$rcpt_to."
    ");
     87                 $sent = FALSE;
     88                 continue;
     89             }
     90 
     91             if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $utfheader, $body)) {
     92                 $this->log_write("E-mail has been sent to <".$rcpt_to.">
    ");
     93             } else {
     94                 $this->log_write("Error: Cannot send email to <".$rcpt_to.">
    ");
     95                 $sent = FALSE;
     96             }
     97 
     98             fclose($this->sock);
     99 
    100             $this->log_write("Disconnected from remote host
    ");
    101         }
    102         return $sent;
    103     }
    104 /* Private Functions */
    105     function smtp_send($helo, $from, $to, $header, $body = "")
    106     {
    107         if (!$this->smtp_putcmd("HELO", $helo)) {
    108 
    109             return $this->smtp_error("sending HELO command");
    110         }
    111 
    112         #auth
    113 
    114         if($this->auth){
    115             if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
    116                 return $this->smtp_error("sending HELO command");
    117             }
    118 
    119             if (!$this->smtp_putcmd("", base64_encode($this->pass))) {
    120                 return $this->smtp_error("sending HELO command");
    121             }
    122         }
    123 
    124         #
    125 
    126         if (!$this->smtp_putcmd("MAIL", "FROM:<".$from.">")) {
    127             return $this->smtp_error("sending MAIL FROM command");
    128         }
    129 
    130         if (!$this->smtp_putcmd("RCPT", "TO:<".$to.">")) {
    131             return $this->smtp_error("sending RCPT TO command");
    132         }
    133 
    134         if (!$this->smtp_putcmd("DATA")) {
    135             return $this->smtp_error("sending DATA command");
    136         }
    137         if (!$this->smtp_message($header, $body)) {
    138             return $this->smtp_error("sending message");
    139         }
    140         if (!$this->smtp_eom()) {
    141             return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]");
    142         }
    143         if (!$this->smtp_putcmd("QUIT")) {
    144             return $this->smtp_error("sending QUIT command");
    145         }
    146         return TRUE;
    147     }
    148 
    149     function smtp_sockopen($address)
    150     {
    151         if ($this->relay_host == "") {
    152             return $this->smtp_sockopen_mx($address);
    153         } else {
    154             return $this->smtp_sockopen_relay();
    155         }
    156     }
    157     function smtp_sockopen_relay()
    158     {
    159         $this->log_write("Trying to ".$this->relay_host.":".$this->smtp_port."
    ");
    160         $this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);
    161         if (!($this->sock && $this->smtp_ok())) {
    162             $this->log_write("Error: Cannot connenct to relay host ".$this->relay_host."
    ");
    163             $this->log_write("Error: ".$errstr." (".$errno.")
    ");
    164             return FALSE;
    165         }
    166         $this->log_write("Connected to relay host ".$this->relay_host."
    ");
    167         return TRUE;
    168     }
    169 
    170     function smtp_sockopen_mx($address)
    171     {
    172         $domain = ereg_replace("^.+@([^@]+)$", "1", $address);
    173         if (!@getmxrr($domain, $MXHOSTS)) {
    174             $this->log_write("Error: Cannot resolve MX "".$domain.""
    ");
    175             return FALSE;
    176         }
    177         foreach ($MXHOSTS as $host) {
    178             $this->log_write("Trying to ".$host.":".$this->smtp_port."
    ");
    179             $this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
    180             if (!($this->sock && $this->smtp_ok())) {
    181                 $this->log_write("Warning: Cannot connect to mx host ".$host."
    ");
    182                 $this->log_write("Error: ".$errstr." (".$errno.")
    ");
    183                 continue;
    184             }
    185             $this->log_write("Connected to mx host ".$host."
    ");
    186             return TRUE;
    187         }
    188         $this->log_write("Error: Cannot connect to any mx hosts (".implode(", ", $MXHOSTS).")
    ");
    189         return FALSE;
    190     }
    191 
    192     function smtp_message($header, $body)
    193     {
    194         fputs($this->sock, $header."
    ".$body);
    195         $this->smtp_debug("> ".str_replace("
    ", "
    "."> ", $header."
    > ".$body."
    > "));
    196         return TRUE;
    197     }
    198 
    199     function smtp_eom()
    200     {
    201         fputs($this->sock, "
    .
    ");
    202         $this->smtp_debug(". [EOM]
    ");
    203         return $this->smtp_ok();
    204     }
    205 
    206     function smtp_ok()
    207     {
    208         $response = str_replace("
    ", "", fgets($this->sock, 512));
    209         $this->smtp_debug($response."
    ");
    210         if (!ereg("^[23]", $response)) {
    211             fputs($this->sock, "QUIT
    ");
    212             fgets($this->sock, 512);
    213             $this->log_write("Error: Remote host returned "".$response.""
    ");
    214             return FALSE;
    215         }
    216         return TRUE;
    217     }
    218 
    219     function smtp_putcmd($cmd, $arg = "")
    220     {
    221         if ($arg != "") {
    222             if($cmd=="") $cmd = $arg;
    223             else $cmd = $cmd." ".$arg;
    224         }
    225         fputs($this->sock, $cmd."
    ");
    226         $this->smtp_debug("> ".$cmd."
    ");
    227         return $this->smtp_ok();
    228     }
    229 
    230     function smtp_error($string)
    231     {
    232         $this->log_write("Error: Error occurred while ".$string.".
    ");
    233         return FALSE;
    234     }
    235     
    236     function log_write($message)
    237     {
    238         $this->smtp_debug($message);
    239         if ($this->log_file == "") {
    240             return TRUE;
    241         }
    242         $message = date("M d H:i:s ").get_current_user()."[".getmypid()."]: ".$message;
    243         if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {
    244             $this->smtp_debug("Warning: Cannot open log file "".$this->log_file.""
    ");
    245             return FALSE;;
    246         }
    247         flock($fp, LOCK_EX);
    248         fputs($fp, $message);
    249         fclose($fp);
    250         return TRUE;
    251     }
    252     
    253     function strip_comment($address)
    254     {
    255         $comment = "([^()]*)";
    256         while (ereg($comment, $address)) {
    257             $address = ereg_replace($comment, "", $address);
    258         }
    259         return $address;
    260     }
    261 
    262     function get_address($address)
    263     {
    264         $address = ereg_replace("([ 	
    ])+", "", $address);
    265         $address = ereg_replace("^.*<(.+)>.*$", "1", $address);
    266         return $address;
    267     }
    268     function smtp_debug($message)
    269     {
    270         if ($this->debug) {
    271         echo $message;
    272         }
    273     }
    274 }
    275 ?>
    Stmp.class.php

    2、设置配置文件 CommomConf 目录下的 config.php

     1 // 配置邮件发送服务器
     2         'THINK_EMAIL' => array(
     3                              'SMTP_HOST'   => 'smtp.163.com', //SMTP服务器
     4                              'SMTP_PORT'   => '25', //SMTP服务器端口
     5                              'SMTP_USER'   => '*******@163.com', //SMTP服务器用户名,你的邮箱名
     6                              'SMTP_PASS'   => '*******', //SMTP服务器密码,邮箱密码
     7                              'FROM_EMAIL'  => '********@163.com', //发件人EMAIL
     8                              'FROM_NAME'   => '********', //发件人名称
     9                              'REPLY_EMAIL' => '', //回复EMAIL(留空则为发件人EMAIL)
    10                              'REPLY_NAME'  => '', //回复名称(留空则为发件人名称)
    11         ),

    3、具体使用

    /*
         * 【执行发送邮箱验证码】
         *
         * @access private
         * @param string $smtpemailto     收件人邮箱
         * @param string $mailsubject     邮件主题
         * @param string $mailbody        邮件内容
         * @param string $mailtype         邮件格式
         * @return boolean
         * 
         **/
        private function executeSendEmailCode($smtpemailto, $mailsubject, $mailbody, $mailtype = "HTML"){
            $config_mail = C('THINK_EMAIL');//获取配置信息
            $smtpserver     =     $config_mail['SMTP_HOST'];//SMTP服务器
            $smtpserverport =    $config_mail['SMTP_PORT'];//SMTP服务器端口
            $smtpusermail     =     $config_mail['FROM_EMAIL'];//SMTP服务器的用户邮箱
            $smtpuser         =     $config_mail['SMTP_USER'];//SMTP服务器的用户帐号
            $smtppass         =     $config_mail['SMTP_PASS'];//SMTP服务器的用户密码
            
    
            $mailtime        =    date("Y-m-d H:i:s");
    
            
            $utfmailbody    =    iconv("UTF-8","GB2312",$mailbody);//转换邮件编码
    //         $mailtype         =     "HTML";//邮件格式(HTML/TXT),TXT为文本邮件
       
            
            $smtp = new Smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
            $smtp->debug = FALSE;//是否显示发送的调试信息 FALSE or TRUE
            
            $ret = $smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $utfmailbody, $mailtype);
            
            return  $ret;
        }

    2016-09-28

  • 相关阅读:
    WPF关于改变ListBoxItem的颜色的注意事项以及如何找到ListBox中的ItemsPanel
    WPF中关于配置文件的读取
    C++虚函数和虚函数表
    gdb调试技巧
    libevent和基于libevent的网络编程
    Reactor模式详解
    Ubuntu Linux 下文件名乱码(无效的编码)的快速解决办法
    Linux进程间通信——使用共享内存
    Linux进程间通信——使用信号量
    布隆过滤器(Bloom Filter)详解
  • 原文地址:https://www.cnblogs.com/reader/p/5915388.html
Copyright © 2011-2022 走看看