首頁 後端開發 php教程 如何使用php中smtp發送支援附件的郵件

如何使用php中smtp發送支援附件的郵件

Jun 13, 2018 pm 02:25 PM
php發送郵件

這篇文章主要介紹了php使用smtp發送支援附件的郵件範例,需要有smtp伺服器,程式碼經過多次實戰使用,需要的朋友可以參考下

輕量級PHP郵件發送,需要有smtp伺服器,程式碼經過多次實戰使用,現在把程式碼分享給大家

<?php
/*
邮件发送smtp服务
联结smtp服务器,进行邮件发送,版权所有,不能复制
@author:jackbrown;
@qq: 610269963 
@time:2011-8-20;
@version:1.0.3;
*/
class smtp{

 /*邮件用户名*/
 public $mailUser = MAIL_USER;

 /*邮件密码*/
 public $mailPwd = MAIL_PWD;

 /*邮件服务器地址*/
 public $server = MAIL_SMTP_HOST;

 /*邮件端口*/
 public $port = MAIL_SMTP_PORT;

 public $timeout = MAIL_TIMEOUT;

 /*邮件编码*/
 public $charset = MAIL_CHARSET;

 /*邮件发送者email,用于显示给接收者*/
 public $senderMail = MAIL_SENDER;

 /*发用者名称*/
 public $senderName = MAIL_SENDER_NAME;

 /*是否使用ssl安全操作*/
 public $useSSL = IN_SSL;

 /*是否显示错误信息*/
 public $showError = MAIL_SHOW_ERR;

 public $needLogin = MAIL_NEED_LOGIN;

 /*附件数组*/
 public $attachMent = array();

 public $failed = false;

 private static $smtpCon;
 private $stop ="\r\n";
 private $status = 0;

 

 public function __construct(){

  if(self::$smtpCon){
   return;
  }

  if($this->mailUser==&#39;&#39;){
   $this->error(&#39;请配置好邮件登录用户名!&#39;);
   return false; 
  }

  if($this->mailPwd==&#39;&#39;){  
   $this->error(&#39;请配置好邮件登录密码!&#39;);
   return false; 
  }

  if($this->server==&#39;&#39;){   
   $this->error(&#39;请配置好邮服务器地址!&#39;);
   return false; 
  }

  if(!is_numeric($this->port)){   
   $this->error(&#39;请配置好邮服务器端口!&#39;);
   return false; 
  }

  /*ssl使用**/
  $server = $this->server;
  if($this->useSSL == true){
   $server = "ssl://".$this->server; 
  }

  self::$smtpCon = @fsockopen($server, $this->port, $errno, $errstr,10);;

  
  if(!self::$smtpCon){
   $this->error($errno.$errstr); 
   return false;
  }

  
  socket_set_timeout(self::$smtpCon,0,250000);

  /*开始邮件指令*/
  $this->getStatus();
  $resp = true;
  $resp = $resp && $this->helo();
  if($this->needLogin == &#39;1&#39;){
   $resp = $resp && $this->login();
  }

  if(!$resp){
   $this->failed = true;
  }

 }

 /*
 发送邮件
 @param string $to 接收邮件地址
 @param string $msg 邮件主要内容
 @title string $title 邮件标题
 */
 public function sendMail($to,$msg,$title=&#39;&#39;){

  if($msg==&#39;&#39; ){

   return false;
  }
  if(is_array($to)){

   if($to!=null){
    foreach($to as $k=>$e){

     if(!preg_match(&#39;/^[a-z0-9A-Z_-]+@+([a-z0-9A-Z_-]+\.)+[a-z0-9A-Z]{2,3}$/&#39;,$e)){

      unset($to[$k]);
     }
    }
   }else{
    return false;
   }

   if($to == null){
    return false;
   }

  }else{

   if(!preg_match(&#39;/^[a-z0-9A-Z_-]+@+([a-z0-9A-Z_-]+\.)+[a-z0-9A-Z]{2,3}$/&#39;,$to)){

    return false;
   }

  }

   
  if(!self::$smtpCon){
   return false;
  }

  $this->sendSmtpMsg(&#39;MAIL FROM:<&#39;.$this->senderMail.&#39;>&#39;);

  if(!is_array($to)){      
   $this->sendSmtpMsg(&#39;RCPT TO:<&#39;.$to.&#39;>&#39;);
  }else{

   foreach($to as $k=>$email){    
    $this->sendSmtpMsg(&#39;RCPT TO:<&#39;.$email.&#39;>&#39;); 
   }
  }

  $this->sendSmtpMsg("DATA");

 
  if($this->status !=&#39;354&#39;){
   $this->error(&#39;请求发送邮件失败!&#39;);
   $this->failed = true;
   return false; 
  }

  $msg  = base64_encode($msg);
  $msg = str_replace($this->stop . &#39;.&#39;, $this->stop . &#39;..&#39;, $msg);
  $msg    = substr($msg, 0, 1) == &#39;.&#39; ? &#39;.&#39; . $msg : $msg;

  if($this->attachMent!=null){

   $headers = $this->mimeHeader($msg,$to,$title);
   $this->sendSmtpMsg($headers,false); 

  }else{

   $headers = $this->mailHeader($to,$title);
   $this->sendSmtpMsg($headers,false); 
   $this->sendSmtpMsg(&#39;&#39;,false);
   $this->sendSmtpMsg($msg,false);
  }
  $this->sendSmtpMsg(&#39;.&#39;);//发送结束标识符

  if($this->status != &#39;250&#39;){
   $this->failed = true;
   $this->error($this->readSmtpMsg());
   return false; 
  }

  return true;
 }

 /*
 关闭邮件连接
 */
 public function close(){

  $this->sendSmtpMsg(&#39;Quite&#39;);
  @socket_close(self::$smtpCon);
 }

 /*
 添加普通邮件头信息
 */
 protected function mailHeader($to,$title){
  $headers = array();
  $headers[] = &#39;Date: &#39;.$this->gmtime(&#39;D j M Y H:i:s&#39;).&#39; &#39;.date(&#39;O&#39;);

  if(!is_array($to)){
   $headers[] = &#39;To: "&#39;.&#39;=?&#39;.$this->charset.&#39;?B?&#39;.base64_encode($this->getMailUser($to)).&#39;?="<&#39;.$to.&#39;>&#39;;
  }else{
   foreach($to as $k=>$e){
    $headers[] = &#39;To: "&#39;.&#39;=?&#39;.$this->charset.&#39;?B?&#39;.base64_encode($this->getMailUser($e)).&#39;?="<&#39;.$e.&#39;>&#39;;
   }
  }

  $headers[] = &#39;From: "=?&#39;.$this->charset.&#39;?B?&#39;.base64_encode($this->senderName).&#39;?="<&#39;.$this->senderMail.&#39;>&#39;;
  $headers[] = &#39;Subject: =?&#39;.$this->charset.&#39;?B?&#39;.base64_encode($title).&#39;?=&#39;;
  $headers[] = &#39;Content-type: text/html; charset=&#39;.$this->charset.&#39;; format=flowed&#39;; 
  $headers[] = &#39;Content-Transfer-Encoding: base64&#39;; 

     $headers = str_replace($this->stop . &#39;.&#39;, $this->stop . &#39;..&#39;, trim(implode($this->stop, $headers)));
  return $headers;
 }

 /*
 带付件的头部信息
 */
 protected function mimeHeader($msg,$to,$title){

  if($this->attachMent!=null){

   $headers = array();
   $boundary = &#39;----=&#39;.uniqid();
   $headers[] = &#39;Date: &#39;.$this->gmtime(&#39;D j M Y H:i:s&#39;).&#39; &#39;.date(&#39;O&#39;);  
   if(!is_array($to)){
    $headers[] = &#39;To: "&#39;.&#39;=?&#39;.$this->charset.&#39;?B?&#39;.base64_encode($this->getMailUser($to)).&#39;?="<&#39;.$to.&#39;>&#39;;
   }else{
    foreach($to as $k=>$e){
     $headers[] = &#39;To: "&#39;.&#39;=?&#39;.$this->charset.&#39;?B?&#39;.base64_encode($this->getMailUser($e)).&#39;?="<&#39;.$e.&#39;>&#39;;
    }
   }

   $headers[] = &#39;From: "=?&#39;.$this->charset.&#39;?B?&#39;.base64_encode($this->senderName).&#39;?="<&#39;.$this->senderMail.&#39;>&#39;;
   $headers[] = &#39;Subject: =?&#39;.$this->charset.&#39;?B?&#39;.base64_encode($title).&#39;?=&#39;;
   $headers[] =  &#39;Mime-Version: 1.0&#39;;
   $headers[] = &#39;Content-Type: multipart/mixed;boundary="&#39;.$boundary.&#39;"&#39;.$this->stop;
   $headers[]=&#39;--&#39;.$boundary;

   $headers[]=&#39;Content-Type: text/html;charset="&#39;.$this->charset.&#39;"&#39;;
   $headers[]=&#39;Content-Transfer-Encoding: base64&#39;.$this->stop;
   $headers[] = &#39;&#39;;
   $headers[]= $msg.$this->stop;   

   foreach($this->attachMent as $k=>$filename){

    $f = @fopen($filename, &#39;r&#39;);
    $mimetype = $this->getMimeType(realpath($filename));
    $mimetype = $mimetype == &#39;&#39; ? &#39;application/octet-stream&#39; : $mimetype;

    $attachment = @fread($f, filesize($filename));
    $attachment = base64_encode($attachment);
    $attachment = chunk_split($attachment);

    $headers[] = "--" . $boundary;
    $headers[] = "Content-type: ".$mimetype.";name=\"=?".$this->charset."?B?". base64_encode(basename($filename)).&#39;?="&#39; ;
    $headers[] = "Content-disposition: attachment; name=\"=?".$this->charset."?B?". base64_encode(basename($filename)).&#39;?="&#39;;
    $headers[] = &#39;Content-Transfer-Encoding: base64&#39;.$this->stop;
    $headers[] = $attachment.$this->stop;

    

   }
   $headers[] = "--" . $boundary . "--";
   $headers = str_replace($this->stop . &#39;.&#39;, $this->stop . &#39;..&#39;, trim(implode($this->stop, $headers)));
   return $headers;

  }  
 }

 /*
 获取返回状态
 */
 protected function getStatus(){

  $this->status = substr($this->readSmtpMsg(),0,3);
 }

 
 /*
 获取邮件服务器返回的信息
 @return string 信息字符串
 */
 protected function readSmtpMsg(){

  if(!is_resource(self::$smtpCon)){
   return false;
  } 

  $return = &#39;&#39;;
  $line   = &#39;&#39;;
  while (strpos($return, $this->stop)=== false OR $line{3}!== &#39; &#39;)
  {
   $line    = fgets(self::$smtpCon, 512);
   $return .= $line;
  }

  return trim($return);  

 }

 /*
 给邮件服务器发给指定命令消息
 */
 protected function sendSmtpMsg($cmd,$chStatus=true){
        if (is_resource(self::$smtpCon))
        {
             fwrite(self::$smtpCon, $cmd . $this->stop, strlen($cmd) + 2);
        }
  if($chStatus == true){
   $this->getStatus();
  }

  return true;
 }

 /*
 邮件时间格式
 */
 protected function gmtime(){

  return (time() - date(&#39;Z&#39;));

 }

 /*
 获取付件的mime类型
 */
 protected function getMimeType($file){

  $mimes = array(
   &#39;chm&#39;=>&#39;application/octet-stream&#39;, &#39;ppt&#39;=>&#39;application/vnd.ms-powerpoint&#39;, 
   &#39;xls&#39;=>&#39;application/vnd.ms-excel&#39;, &#39;doc&#39;=>&#39;application/msword&#39;, &#39;exe&#39;=>&#39;application/octet-stream&#39;, 
   &#39;rar&#39;=>&#39;application/octet-stream&#39;, &#39;js&#39;=>"javascrīpt/js", &#39;css&#39;=>"text/css", 
   &#39;hqx&#39;=>"application/mac-binhex40", &#39;bin&#39;=>"application/octet-stream", &#39;oda&#39;=>"application/oda", &#39;pdf&#39;=>"application/pdf", 
   &#39;ai&#39;=>"application/postsrcipt", &#39;eps&#39;=>"application/postsrcipt", &#39;es&#39;=>"application/postsrcipt", &#39;rtf&#39;=>"application/rtf", 
   &#39;mif&#39;=>"application/x-mif", &#39;csh&#39;=>"application/x-csh", &#39;dvi&#39;=>"application/x-dvi", &#39;hdf&#39;=>"application/x-hdf", 
   &#39;nc&#39;=>"application/x-netcdf", &#39;cdf&#39;=>"application/x-netcdf", &#39;latex&#39;=>"application/x-latex", &#39;ts&#39;=>"application/x-troll-ts", 
   &#39;src&#39;=>"application/x-wais-source", &#39;zip&#39;=>"application/zip", &#39;bcpio&#39;=>"application/x-bcpio", &#39;cpio&#39;=>"application/x-cpio", 
   &#39;gtar&#39;=>"application/x-gtar", &#39;shar&#39;=>"application/x-shar", &#39;sv4cpio&#39;=>"application/x-sv4cpio", &#39;sv4crc&#39;=>"application/x-sv4crc", 
   &#39;tar&#39;=>"application/x-tar",&#39;ustar&#39;=>"application/x-ustar",&#39;man&#39;=>"application/x-troff-man", &#39;sh&#39;=>"application/x-sh", 
   &#39;tcl&#39;=>"application/x-tcl", &#39;tex&#39;=>"application/x-tex", &#39;texi&#39;=>"application/x-texinfo",&#39;texinfo&#39;=>"application/x-texinfo", 
   &#39;t&#39;=>"application/x-troff", &#39;tr&#39;=>"application/x-troff", &#39;roff&#39;=>"application/x-troff", 
   &#39;shar&#39;=>"application/x-shar", &#39;me&#39;=>"application/x-troll-me", &#39;ts&#39;=>"application/x-troll-ts", 
   &#39;gif&#39;=>"image/gif", &#39;jpeg&#39;=>"image/pjpeg", &#39;jpg&#39;=>"image/pjpeg", &#39;jpe&#39;=>"image/pjpeg", &#39;ras&#39;=>"image/x-cmu-raster", 
   &#39;pbm&#39;=>"image/x-portable-bitmap", &#39;ppm&#39;=>"image/x-portable-pixmap", &#39;xbm&#39;=>"image/x-xbitmap", &#39;xwd&#39;=>"image/x-xwindowdump", 
   &#39;ief&#39;=>"image/ief", &#39;tif&#39;=>"image/tiff", &#39;tiff&#39;=>"image/tiff", &#39;pnm&#39;=>"image/x-portable-anymap", &#39;pgm&#39;=>"image/x-portable-graymap", 
   &#39;rgb&#39;=>"image/x-rgb", &#39;xpm&#39;=>"image/x-xpixmap", &#39;txt&#39;=>"text/plain", &#39;c&#39;=>"text/plain", &#39;cc&#39;=>"text/plain", 
   &#39;h&#39;=>"text/plain", &#39;html&#39;=>"text/html", &#39;htm&#39;=>"text/html", &#39;htl&#39;=>"text/html", &#39;rtx&#39;=>"text/richtext", &#39;etx&#39;=>"text/x-setext", 
   &#39;tsv&#39;=>"text/tab-separated-values", &#39;mpeg&#39;=>"video/mpeg", &#39;mpg&#39;=>"video/mpeg", &#39;mpe&#39;=>"video/mpeg", &#39;avi&#39;=>"video/x-msvideo", 
   &#39;qt&#39;=>"video/quicktime", &#39;mov&#39;=>"video/quicktime", &#39;moov&#39;=>"video/quicktime", &#39;movie&#39;=>"video/x-sgi-movie", &#39;au&#39;=>"audio/basic", 
   &#39;snd&#39;=>"audio/basic", &#39;wav&#39;=>"audio/x-wav", &#39;aif&#39;=>"audio/x-aiff", &#39;aiff&#39;=>"audio/x-aiff", &#39;aifc&#39;=>"audio/x-aiff", 
   &#39;swf&#39;=>"application/x-shockwave-flash", &#39;myz&#39;=>"application/myz" 
  );

  $ext = substr(strrchr($file,&#39;.&#39;),1);
  $type = $mimes[$ext];

  
  unset($mimes);
  return $type;
 }

 /*
 邮件helo命令
 */
 private function helo(){

  if($this->status != &#39;220&#39;){

   $this->error(&#39;连接服务器失败!&#39;); 
   return false;
  }

  return $this->sendSmtpMsg(&#39;HELO &#39;.$this->server);

 }

 
 /*
 登录
 */
 private function login(){

  if($this->status!=&#39;250&#39;){

   $this->error(&#39;helo邮件指令失败!&#39;);
   return false;
  }

  $this->sendSmtpMsg(&#39;AUTH LOGIN&#39;);  
  if($this->status!=&#39;334&#39;){
   $this->error(&#39;AUTH LOGIN 邮件指令失败!&#39;);
   return false;
  }

  $this->sendSmtpMsg(base64_encode($this->mailUser));  
  if($this->status!=&#39;334&#39;){
   $this->error(&#39;邮件登录用户名可能不正确!&#39;.$this->readSmtpMsg());
   return false;
  }

  $this->sendSmtpMsg(base64_encode($this->mailPwd));
  if($this->status !=&#39;235&#39;){
   $this->error(&#39;邮件登录密码可能不正确!&#39;);
   return false;
  }

  return true;

 }

 private function getMailUser($to){

  $temp = explode(&#39;@&#39;,$to);
  return $temp[0];
 }
 /*
 异常报告
 */
 private function error($exception){ 

  if($this->showError == false){
   file_put_contents(&#39;mail_log.txt&#39;,$exception,FILE_APPEND);
   return;
  }

  if(class_exists(&#39;error&#39;) && is_object($GLOBALS[&#39;error&#39;])){   
   $GLOBALS[&#39;error&#39;]->showErrorStr($exception,&#39;javascript:&#39;,false);
  }else{
   throw new Exception($exception);
  }
 }

}
// 使用示例 
ini_set(&#39;memory_limit&#39;,&#39;128M&#39;);
set_time_limit(120);
define(&#39;MAIL_SENDER_NAME&#39;,&#39;楚贤&#39;);
define(&#39;MAIL_SMTP_HOST&#39;,&#39;smtp.ym.163.com&#39;);
define(&#39;MAIL_USER&#39;,&#39;admin@myxxxx.com&#39;);
define(&#39;MAIL_SENDER&#39;,&#39;admin@myxxxx.com&#39;);
define(&#39;MAIL_PWD&#39;,&#39;xxxx&#39;);
define(&#39;MAIL_SMTP_PORT&#39;,25);
define(&#39;IN_SSL&#39;,false);
define(&#39;MAIL_TIMEOUT&#39;,10);
define(&#39;MAIL_CHARSET&#39;,&#39;utf-8&#39;);
date_default_timezone_set(&#39;PRC&#39;);
$m = new smtp();
$msg = "有用户登录服务器@".date(&#39;Y-m-d H:i:s&#39;);
付件
//$m->attachMent = array(&#39;hehe.php&#39;,&#39;common.php&#39;);
if($m->sendMail(array(&#39;610269963@qq.com&#39;),$msg,&#39;88服务器登录提示&#39;)){
 echo &#39;发送成功!&#39;;
}
$m->close();
?>
登入後複製

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

使用laravel sms 建立簡訊驗證碼發送校驗的功能

##如何解決PHP中Fatal error session_start()的錯誤

#關於PHP的autoLoad自動載入機制的分析

以上是如何使用php中smtp發送支援附件的郵件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

在PHP API中說明JSON Web令牌(JWT)及其用例。 在PHP API中說明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一種基於JSON的開放標準,用於在各方之間安全地傳輸信息,主要用於身份驗證和信息交換。 1.JWT由Header、Payload和Signature三部分組成。 2.JWT的工作原理包括生成JWT、驗證JWT和解析Payload三個步驟。 3.在PHP中使用JWT進行身份驗證時,可以生成和驗證JWT,並在高級用法中包含用戶角色和權限信息。 4.常見錯誤包括簽名驗證失敗、令牌過期和Payload過大,調試技巧包括使用調試工具和日誌記錄。 5.性能優化和最佳實踐包括使用合適的簽名算法、合理設置有效期、

會話如何劫持工作,如何在PHP中減輕它? 會話如何劫持工作,如何在PHP中減輕它? Apr 06, 2025 am 12:02 AM

會話劫持可以通過以下步驟實現:1.獲取會話ID,2.使用會話ID,3.保持會話活躍。在PHP中防範會話劫持的方法包括:1.使用session_regenerate_id()函數重新生成會話ID,2.通過數據庫存儲會話數據,3.確保所有會話數據通過HTTPS傳輸。

描述紮實的原則及其如何應用於PHP的開發。 描述紮實的原則及其如何應用於PHP的開發。 Apr 03, 2025 am 12:04 AM

SOLID原則在PHP開發中的應用包括:1.單一職責原則(SRP):每個類只負責一個功能。 2.開閉原則(OCP):通過擴展而非修改實現變化。 3.里氏替換原則(LSP):子類可替換基類而不影響程序正確性。 4.接口隔離原則(ISP):使用細粒度接口避免依賴不使用的方法。 5.依賴倒置原則(DIP):高低層次模塊都依賴於抽象,通過依賴注入實現。

PHP 8.1中的枚舉(枚舉)是什麼? PHP 8.1中的枚舉(枚舉)是什麼? Apr 03, 2025 am 12:05 AM

PHP8.1中的枚舉功能通過定義命名常量增強了代碼的清晰度和類型安全性。 1)枚舉可以是整數、字符串或對象,提高了代碼可讀性和類型安全性。 2)枚舉基於類,支持面向對象特性,如遍歷和反射。 3)枚舉可用於比較和賦值,確保類型安全。 4)枚舉支持添加方法,實現複雜邏輯。 5)嚴格類型檢查和錯誤處理可避免常見錯誤。 6)枚舉減少魔法值,提升可維護性,但需注意性能優化。

在PHPStorm中如何進行CLI模式的調試? 在PHPStorm中如何進行CLI模式的調試? Apr 01, 2025 pm 02:57 PM

在PHPStorm中如何進行CLI模式的調試?在使用PHPStorm進行開發時,有時我們需要在命令行界面(CLI)模式下調試PHP�...

如何在系統重啟後自動設置unixsocket的權限? 如何在系統重啟後自動設置unixsocket的權限? Mar 31, 2025 pm 11:54 PM

如何在系統重啟後自動設置unixsocket的權限每次系統重啟後,我們都需要執行以下命令來修改unixsocket的權限:sudo...

解釋PHP中的晚期靜態綁定(靜態::)。 解釋PHP中的晚期靜態綁定(靜態::)。 Apr 03, 2025 am 12:04 AM

靜態綁定(static::)在PHP中實現晚期靜態綁定(LSB),允許在靜態上下文中引用調用類而非定義類。 1)解析過程在運行時進行,2)在繼承關係中向上查找調用類,3)可能帶來性能開銷。

See all articles