1. 程式人生 > >關於 PHPMailer 郵件發送類的使用心得(含多文件上傳)

關於 PHPMailer 郵件發送類的使用心得(含多文件上傳)

登錄 subst PE 絕對路徑 cde focus test explode 大量

Is this important for send mail

  • PHPMailer 核心文件

    • class.phpmailer.php

    • class.phpmaileroauth.php

    • class.phpmaileroauthgoogle.php

    • class.pop3.php

    • class.smtp.php

    • get_oauth_token.php

    • PHPMailerAutoload.php

  • 在使用PHPMailer之前,首先查看PHP環境擴展中是否開啟了socketopenssl擴展,如若沒有開啟,請在php.ini配置文件中開啟兩者擴展支持

  • 大多數主流郵箱都支持SMTP協議,除去QQ郵箱,在作為三方代發郵箱時,需要開啟SMTP服務支持,並需要授權碼登錄使用郵箱。對於其他像163、sina等郵箱直接使用代發郵箱賬號和密碼即可。

    • code of demo

    • <?php
      // 引入PHPMailer核心類文件(SMTP協議方式)
      require_once(‘class.phpmailer.php‘);
      require_once(‘class.smtp.php‘);
      
      $mail = new PHPMailer();
      
      // 是否開啟debug調試模式,默認為false,非開發環境建議關閉
      $mail->SMTPDebug = 0;
      
      // 使用SMTP鑒權方式發送郵件(通用必寫方法)
      $mail->isSMTP();
      
      // 一旦使用SMTP鑒權方式,必須為True(通用必寫方法)
      $mail->SMTPAuth = true
      ; /** * 以下開始分為QQ郵箱和非QQ郵箱方式,以sina郵箱為例 * QQ郵箱方式需要使用ssl方式加密登錄,登錄密碼使用所 * 給授權碼,在郵箱設置中的賬號中,開啟IMAP/SMTP服務 * 並驗證密保成功,會給出授權碼 */ // 連接的SMTP服務器主機地址(QQ) $mail->HOST = ‘smtp.qq.com‘; // 設置使用ssl加密方式登錄鑒權(QQ),其他郵箱請註釋或者令屬性值為空 $mail->SMTPSecure = ‘ssl‘; // 設置ssl連接SMTP服務器遠程連接端口號(QQ) $mali->Port = ‘465‘; // 設置發送郵件編碼
      $mail->CharSet = ‘UTF-8‘; // 設置發送人昵稱 $mail->FromName = ‘發件人昵稱‘; // 設置發件人郵箱賬戶 $mail->Usename = ‘[email protected]; // QQ郵箱使用獲取到的授權碼作為賬戶的登錄密碼,其他郵箱使用郵箱密碼登錄即可 $mail->Password = ‘***********‘; //發件人郵箱地址,同發件人郵箱 $mail->From = ‘[email protected]; // 設置郵件正文是否為HTML編碼 $mail->isHTML(true); // 添加收件人郵箱地址,如若需要群發多人,可多次調用此方法即可 $mail->addAddress(‘[email protected]); //$mail->addAddress(‘[email protected]‘); // 設置郵件主題 $mail->Subject = ‘郵件主題‘; // 設置郵件正文(可使用定界符來定義大量正文內容) $mail->Body = <<< EOR <h1>Test mail</h1> EOR; /* 設置郵件附件,此方法兩個參數,分別是附件的位置路徑(絕對或者相對路徑)以及附件的命名,可 多次調用此方法,添加多個附件 */ $mail->addAttachment($path,$name); //$mail->addAttachment($path,$name); // 發送郵件並返回 bool $status = $mail->send(); // 根據返回 bool 值進行判斷操作 if($status){ #code ... $mail->smtpClose(); }else{ echo ‘Send Mail Error! Error Message is ‘.$mail->ErrorInfo; }

    • 常見的(SMTP、POP3)郵箱服務器以及端口
      <?php
      /**
       * 此處列舉的各大主流或者常見的郵箱服務器如果在連接時出現錯誤,請註冊相應郵箱,在其郵箱
       * 設置中查看相應郵箱服務器的主機地址以及端口
       */ 
      sina.com
      POP3服務器地址:pop3.sina.com.cn(端口:110)
      SMTP服務器地址:smtp.sina.com.cn(端口:25) 
          
      sina.cn
      POP3服務器地址:pop3.sina.com(端口:110)      ------- > pop.sina.com
      SMTP服務器地址:smtp.sina.com(端口:25)
          
      sinaVIP
      POP3服務器:pop3.vip.sina.com (端口:110)
      SMTP服務器:smtp.vip.sina.com (端口:25)
      
      sohu.com
      POP3服務器地址:pop3.sohu.com(端口:110)
      SMTP服務器地址:smtp.sohu.com(端口:25)
       
       126郵箱
        POP3服務器地址:pop.126.com(端口:110)
        SMTP服務器地址:smtp.126.com(端口:25)
      
        139郵箱
        POP3服務器地址:POP.139.com(端口:110)
        SMTP服務器地址:SMTP.139.com(端口:25)
            
        163.com
        POP3服務器地址:pop.163.com(端口:110)
        SMTP服務器地址:smtp.163.com(端口:25)
         
        QQ郵箱
        POP3服務器地址:pop.qq.com(端口:110)
        SMTP服務器地址:smtp.qq.com(端口:ssl/465|Tls/587)
      
        QQ企業郵箱
        POP3服務器地址:pop.exmail.qq.com (SSL啟用 端口:995)
        SMTP服務器地址:smtp.exmail.qq.com(SSL啟用 端口:ssl/465|Tls/587)
      
        yahoo.com
        POP3服務器地址:pop.mail.yahoo.com
        SMTP服務器地址:smtp.mail.yahoo.com
      
        yahoo.com.cn
        POP3服務器地址:pop.mail.yahoo.com.cn(端口:995)
        SMTP服務器地址:smtp.mail.yahoo.com.cn(端口:587
      
        HotMail
        POP3服務器地址:pop3.live.com(端口:995)
        SMTP服務器地址:smtp.live.com(端口:587)
      
        gmail(google.com)
        POP3服務器地址:pop.gmail.com(SSL啟用端口:995)
        SMTP服務器地址:smtp.gmail.com(SSL啟用 端口:587263.net
        POP3服務器地址:pop3.263.net(端口:110)
        SMTP服務器地址:smtp.263.net(端口:25263.net.cn
        POP3服務器地址:pop.263.net.cn(端口:110)
        SMTP服務器地址:smtp.263.net.cn(端口:25)
      
        x263.net
        POP3服務器地址:pop.x263.net(端口:110)
        SMTP服務器地址:smtp.x263.net(端口:25)
      
        21cn.com
        POP3服務器地址:pop.21cn.com(端口:110)
        SMTP服務器地址:smtp.21cn.com(端口:25)
      
        Foxmail
        POP3服務器地址:POP.foxmail.com(端口:110)
        SMTP服務器地址:SMTP.foxmail.com(端口:25)
      
        china.com
        POP3服務器地址:pop.china.com(端口:110)
        SMTP服務器地址:smtp.china.com(端口:25)
      
        tom.com
        POP3服務器地址:pop.tom.com(端口:110)
        SMTP服務器地址:smtp.tom.com(端口:25)
      
        etang.com
        POP3服務器地址:pop.etang.com(端口:110)
        SMTP服務器地址:smtp.etang.com(端口:25)    

    • 關於表單多文件上傳並發送郵箱 demo

    • <html>
          <head>
              <title></title>
          </head>
          <body>
              <form method="POST" enctype="multipart/form-data" action="form_test.php">
                  <input type="file" name="upload[]" multiple="multiple" />
                  <button type="submit">提交</button>
              </form>
          </body>
      </html>

    • 多文件選擇上傳,表單提交 $_FILES 數據形式打印,如圖
    • 技術分享圖片
    • form_test.php
    • <?php
      header("content-type:text/html;charset=utf-8");
      if($_FILES[‘upload‘][‘error‘][0] == 4){
          echo("<script type=‘text/javascript‘> alert(‘請上傳文件‘); window.history.back();</script>");
          exit;
      }else{
          // 設置文件保存目錄
          $uploaddir = "../upload/file/"; 
          require_once ‘upload_img.php‘;
          $FJ = array();
          for($i=0; $i<count($_FILES[‘upload‘][‘name‘]); $i++) {
      
              if(file_exists($_FILES[‘upload‘][‘tmp_name‘][$i]) && is_uploaded_file($_FILES[‘upload‘][‘tmp_name‘][$i])) 
              {
                  //判斷文件類型
                  if(!in_array(strtolower(fileext($_FILES[‘upload‘][‘name‘][$i])),$type)) 
                  { 
                      $text=implode(",",$type); 
                      $page_result=$text;
                      echo("<script type=‘text/javascript‘> alert(‘請上傳格式為 ".$page_result." 的圖片‘); window.history.back();</script>");
                      exit;
                  }else{
                      //生成目標文件的文件名 
                      $filename=explode(".",$_FILES[‘upload‘][‘name‘][$i]);
                      do 
                      { 
                          $filename[0]=random(10);
                          $name=implode(".",$filename); 
                          $uploadfile=$uploaddir.$name; 
                      } 
                      while(file_exists($uploadfile)); 
                      if (move_uploaded_file($_FILES[‘upload‘][‘tmp_name‘][$i],$uploadfile)) 
                      {   
                             
                          $FJ[] = $uploadfile;
                      }
                  }
              }else{
                  echo("<script type=‘text/javascript‘> alert(‘上傳失敗,請重試‘); window.history.back();</script>");
                  exit;
              } 
          }
      }
      
      // 發送郵件(QQ)
      require_once("class.phpmailer.php");
      require_once("class.smtp.php");
      
      $mail = new PHPMailer();
      $mail->SMTPDebug = 0;
      $mail->isSMTP();
      $mail->SMTPAuth = true;
      $mail->SMTPSecure = ‘ssl‘;
      $mail->Host = ‘smtp.qq.com‘;
      $mail->Port = ‘465‘;
      $mail->CharSet = ‘UTF-8‘;
      $mail->FromName = ‘Form Data‘;
      $mail->Username = ‘發送人郵箱賬戶‘;
      $mail->Password = ‘發件人賬戶授權碼‘;
      $mail->From = ‘發件人郵箱賬戶‘;
      $mail->isHTML(true);
      $mail->addAddress(‘收件人郵箱‘);
      $mail->Subject = ‘mail title‘;
      $mail->Body = ‘<h1>Form Data<h1>‘;
      
      // 根據當前腳本文件位置獲取所需目錄絕對地址
      $Active_path = dirname(dirname(__FILE__));
      
      // 循環拼接附件絕對路徑並調用附件添加方法加入郵件附件中
      for ($i=0; $i < count($FJ) ; $i++) { 
          if(file_exists($FJ[$i])){
              $FJ[$i] = $Active_path.‘/‘.str_replace(‘../‘, ‘‘, $FJ[$i]);
              $mail->addAttachment($FJ[$i]);
          }else{
              continue;
          }    
      }
      
      $status = $mail->send();
      if($status){
          // 發送成功,根據需要是否將上傳附件文件刪除,上傳失敗亦然
          for ($i=0; $i < count($FJ) ; $i++) { 
              if(file_exists($FJ[$i])){
                  unlink($FJ[$i]);
              }    
          }
          echo("<script type=‘text/javascript‘> alert(‘send mail success!‘); window.history.back();</script>");
          exit;
      }else{
          for ($i=0; $i < count($FJ) ; $i++) { 
              if(file_exists($FJ[$i])){
                  unlink($FJ[$i]);
              }
          }
           echo("<script type=‘text/javascript‘> alert(‘send mail fail,please try again!Error message: ‘".$mail->ErrorInfo."‘); window.history.back();</script>");
          exit;
      }

    • upload_img.php
    • <?php 
      //設置允許上傳文件的類型
      $type=array("jpg","gif","bmp","jpeg","png"); 
      
      //獲取文件後綴名函數 
      function fileext($filename) 
      { 
          return substr(strrchr($filename, ‘.‘), 1); 
      } 
      
      //生成隨機文件名函數 
      function random($length) 
      { 
          $hash = ‘SC-‘; 
          $chars = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz‘; 
          $max = strlen($chars) - 1; 
          mt_srand((double)microtime() * 1000000); 
          for($i = 0; $i < $length; $i++) 
          { 
              $hash .= $chars[mt_rand(0, $max)]; 
          } 
          return $hash; 
      } 
      
      // 獲取不同比例的縮略圖
      function ResizeImage($uploadfile,$maxwidth,$maxheight,$name)
      {
          //取得當前圖片大小
          $width = imagesx($uploadfile);
          $height = imagesy($uploadfile);
          $i=0.5;
          //生成縮略圖的大小
          if(($width > $maxwidth) || ($height > $maxheight))
          {
              /*
              $widthratio = $maxwidth/$width;
              $heightratio = $maxheight/$height;
              
              if($widthratio < $heightratio)
              {
                  $ratio = $widthratio;
              }
              else
              {
                   $ratio = $heightratio;
              }
              
              $newwidth = $width * $ratio;
              $newheight = $height * $ratio;
              */
              $newwidth = $width * $i;
              $newheight = $height * $i;
              if(function_exists("imagecopyresampled"))
              {
                  $uploaddir_resize = imagecreatetruecolor($newwidth, $newheight);
                  imagecopyresampled($uploaddir_resize, $uploadfile, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
              }
              else
              {
                  $uploaddir_resize = imagecreate($newwidth, $newheight);
                  imagecopyresized($uploaddir_resize, $uploadfile, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
              }
              
              ImageJpeg ($uploaddir_resize,$name);
              ImageDestroy ($uploaddir_resize);
          }
          else
          {
              ImageJpeg ($uploadfile,$name);
          }
      }
      
      // 此處註釋內容為圖片文件的比例縮放
      // if($_FILES["filename"][‘size‘])
      // {
      //     if($file_type == "image/pjpeg"||$file_type == "image/jpg"|$file_type == "image/jpeg")
      //     {
      //         //$im = imagecreatefromjpeg($_FILES[$upload_input_name][‘tmp_name‘]);
      //         $im = imagecreatefromjpeg($uploadfile);
      //     }
      //     elseif($file_type == "image/x-png")
      //     {
      //         //$im = imagecreatefrompng($_FILES[$upload_input_name][‘tmp_name‘]);
      //         $im = imagecreatefromjpeg($uploadfile);
      //     }
      //     elseif($file_type == "image/gif")
      //     {
      //         //$im = imagecreatefromgif($_FILES[$upload_input_name][‘tmp_name‘]);
      //         $im = imagecreatefromjpeg($uploadfile);
      //     }
      //     else//默認jpg
      //     {
      //         $im = imagecreatefromjpeg($uploadfile);
      //     }
      //     if($im)
      //     {
      //         ResizeImage($im,$pic_width_max,$pic_height_max,$uploadfile_resize);
          
      //         ImageDestroy ($im);
      //     }
      // } 

關於 PHPMailer 郵件發送類的使用心得(含多文件上傳)