搜尋
首頁後端開發php教程PHP的發送郵件類

PHP的發送郵件類別

PHP的發送郵件類別的功能則很強大,不但能發html格式的郵件,還可以發附件
class Email  {   
//---設定全域變數  
var $mailTo = ""; // 收件者   
var $mailCC = ""; // 抄送  
var $mailBCC = ""; // 秘密副本  
var $mailFrom = ""; // 寄件者   
var $mailSubject = ""; // 主題   
var $mailText = ""; // 文字格式的信件主體   
var $mailHTML = ""; // html格式的信件主體
var $mailAttachments = ""; // 附件
/* 函數setTo($inAddress)  :用於處理郵件的位址 參數 $inAddress  
為包涵一個或多個字串,email地址變數,使用逗號來分割多個郵件地址  
預設回傳值為true
************************************************** ********/   
function setTo($inAddress){   
//--用explode()函數依照」,」分割郵件位址   
$addressArray = explode( ",",$inAddress);   
//--透過循環對郵件地址的合法性進行檢查   
for($i=0;$icheckEmail($addressArray[$i])==false) return false;  }  
//--所有合法的email位址存入數組中
$this->mailTo = implode($addressArray, ",");   
return true;  }   
/**************************************************
  函數 setCC($inAddress)  設定抄送人郵件地址  
參數 $inAddress 為包涵一個或多個郵件地址的字串,email地址變數,
使用逗號分割多個郵件地址 預設回傳值為true
************************************************** ************/  
function setCC($inAddress){   
//--用explode()函數依照」,」將郵件位址分割
$addressArray = explode( ",",$inAddress);   
//--透過循環對郵件地址的合法性進行檢查   
for($i=0;$icheckEmail($addressArray[$i])==false) return false;  }   
//--所有合法的email地址存入數組中   
$this->mailCC = implode($addressArray, ",");   
return true;  }   
/***************************************************
函數setBCC($inAddress) 設定秘密抄送位址 參數 $inAddress 為包涵一個或多
個郵件地址的字串,email地址變數,使用逗號來分割多個郵件地址 預設回傳值為
true
******************************************/   
function setBCC($inAddress){   
//--用explode()函數依照」,」分割郵件位址   
$addressArray = explode( ",",$inAddress);   
//--透過循環對郵件地址的合法性進行檢查
for($i=0;$i {  if($this->checkEmail($addressArray[$i])==false)  
return false;   
}   
//--所有合法的email位址存入數組中
$this->mailBCC = implode($addressArray, ",");   
return true;   
}   
/**************************************************** *************
函數setFrom($inAddress):設定寄件者地址  參數 $inAddress 為包涵郵件
位址的字串預設回傳值為true
***************************************/   
function setFrom($inAddress){   
if($this->checkEmail($inAddress)){   
$this->mailFrom = $inAddress;   
return true;  
}  return false;  }   
/**********************
函數 setSubject($inSubject)  用於設定郵件主旨參數$inSubject為字串,
預設回傳的是true  
*******************************************/   
function setSubject($inSubject){  
if(strlen(trim($inSubject)) > 0){  
$this->mailSubject = ereg_replace( "n", "",$inSubject);  
return true;  }  
return false;  }   
/************************************************* ***   
函數setText($inText)  設定文字格式的郵件主體參數 $inText 為文字內容默
傳回確認值為 true
******************************************/   
函數 setText($inText){   
if(strlen(trim($inText)) > 0){   
$this->mailText = $inText;  
回真;  }  
返回假;   
}   
/**********************************   
函數setHTML($inHTML)  設定html格式的郵件主體參數$inHTML為html格式,
預設回傳值為true   
************************************/   
函數 setHTML($inHTML){   
if(strlen(trim($inHTML)) > 0){  
$this->mailHTML = $inHTML;   
回真;  }  
返回假;  }  
/**********************   
函數 setAttachments($inAttachments) 設定郵件的附件 參數$inAttachments
為一個包涵目錄的字串,也可以包涵多個檔案用逗號進行分割 預設回傳值為true
*******************************************/   
函數 setAttachments($inAttachments){   
if(strlen(trim($inAttachments)) > 0){   
$this->mailAttachments = $inAttachments;   
回真;  }   
返回假;  }  
/*********************************   
函數 checkEmail($inAddress) :這個函數我們前面已經呼叫過了,主要就是
用於檢查email地址的合法性   
*****************************************/  
函數 checkEmail($inAddress){   
return (ereg( "^[^@ ]+@([a-zA-Z0-9-]+.)+([a-zA-Z0-9-]{2}|net|com|gov|mil| org|edu|int)$",$inAddress));
  }  
/*************************************************
函數loadTemplate($inFileLocation,$inHash,$inFormat)  讀取暫存檔案並且
取代無用資訊的參數$inFileLocation用於定位檔案的目錄    
$inHash 由於儲存臨時的值  $inFormat 由於放置郵件主體    
************************************************** *********/   
函數 loadTemplate($inFileLocation,$inHash,$inFormat){  
/*  例如郵件內有以下內容:  Dear ~!UserName~,   
您的地址是 ~!UserAddress~  */   
//--其中「~!」為開始標誌「~」為結束標誌   
$templateDelim = "~";   
$templateNameStart = "!";   
//--找出這些地方並把它們替換掉   
$templateLineOut = "";  //--開啟暫存檔   
if($templateFile = fopen($inFileLocation, "r")){  
   while(!feof($templateFile)){   
$templateLine = fgets($templateFile,1000);    
$templateLineArray = 爆炸($templateDelim,$templateLine);   
for( $i=0; $i //-- 尋找起始位置   
if(strcspn($templateLineArray[$i],$templateNameStart)==0){   
//-- 取代對應的值   
$hashName = substr($templateLineArray[$i],1);   
//-- 取代對應的值     
$templateLineArray[$i] = ereg_replace($hashName,(string)$inHash[$hashName],$hashName);  
}  
}   
//-- 輸出字元倉庫並數量   
$templateLineOut .= implode($templateLineArray, "");  
}  //--關閉檔案fclose($templateFile);   
//--設定主體格式(文字或html)   
if( strtoupper($inFormat)== "TEXT" )  
return($this->setText($templateLineOut));   
else if( strtoupper($inFormat)== "HTML" )
return($this->setHTML($templateLineOut));  
}  返回 false;
  }   
/*****************************************
  函數 getRandomBoundary($offset)  傳回一個隨機的邊界值
參數 $offset 為整數 – 用於多管道的呼叫 傳回一個md5()編碼的字串  
****************************************/   
函數 getRandomBoundary($offset = 0){   
//-- 隨機數產生   
srand(時間()+$偏移);   
//--傳回 md5 編碼的 32 位元字元長度的字符串  
return ( "----".(md5(rand())));  }   
/********************************************   
函數: getContentType($inFileName)用來判斷附件的類型  
**********************************************/   
function getContentType($inFileName){   
//--去除路徑   
$inFileName = basename($inFileName);   
//--移除沒有副檔名的檔案   
if(strrchr($inFileName, ".") == false){  
return "application/octet-stream";  
}  
//--提區擴展名並進行判斷   
$extension = strrchr($inFileName, ".");   
switch($extension){   
case ".gif": return "image/gif";  
case ".gz": return "application/x-gzip";  
case ".htm": return "text/html";
  case ".html": return "text/html";   
case ".jpg": return "image/jpeg";   
case ".tar": return "application/x-tar";   
case ".txt": return "text/plain";   
case ".zip": return "application/zip";   
default: return "application/octet-stream";   
}   
return "application/octet-stream";   
}   
/**********************************************
函數formatTextHeader把文字內容加上text的文件頭   
************************************************** ***/   
function formatTextHeader(){  $outTextHeader = "";   
$outTextHeader .= "Content-Type: text/plain;  
charset=us-asciin";   
$outTextHeader .= "Content-Transfer-Encoding: 7bitnn";  
$outTextHeader .= $this->mailText. "n";  
return $outTextHeader;   
}  /************************************************  
函式formatHTMLHeader()把郵件主體內容加上html的檔案頭
******************************************/   
function formatHTMLHeader(){   
$outHTMLHeader = "";   
$outHTMLHeader .= "Content-Type: text/html;  
charset=us-asciin";   
$outHTMLHeader .= "Content-Transfer-Encoding: 7bitnn";  
$outHTMLHeader .= $this->mailHTML. "n";   
return $outHTMLHeader;  
}   
/**********************************   
函數 formatAttachmentHeader($inFileLocation)  把郵件中的附件標示出來  
********************************/   
function formatAttachmentHeader($inFileLocation){   
$outAttachmentHeader = "";  
//--用上面的函數getContentType($inFileLocation)得出附件類型  
$contentType = $this->getContentType($inFileLocation);   
//--若附件是文字型則用標準的7位元編碼   
if(ereg( "text",$contentType)){     
$outAttachmentHeader .= "Content-Type: ".$contentType. ";n";  
$outAttachmentHeader .= ' name="'.basename($inFileLocation). '"'. "n";
  $outAttachmentHeader .= "Content-Transfer-Encoding: 7bitn";   
$outAttachmentHeader .= "Content-Disposition: attachment;n";  
  $outAttachmentHeader .= ' filename="'.basename($inFileLocation). '"'. "nn";  
$textFile = fopen($inFileLocation, "r");   
  while(!feof($textFile)){   
  $outAttachmentHeader .= fgets($textFile,1000);
  }   
//--關閉檔案 fclose($textFile);  
$outAttachmentHeader .= "n";  
}  
//--非文字格式則以64位元進行編碼  
else{  $outAttachmentHeader .= "Content-Type: ".$contentType. ";n";  
$outAttachmentHeader .= ' name="'.basename($inFileLocation). '"'. "n";
  $outAttachmentHeader .= "Content-Transfer-Encoding: base64n";  
$outAttachmentHeader .= "Content-Disposition: attachment;n";  
  $outAttachmentHeader .= ' filename="'.basename($inFileLocation). '"'. "nn";
//--呼叫外部指令uuencode進行編碼
exec( "uuencode -m $inFileLocation nothing_out",$returnArray);  
  for ($i = 1; $i $outAttachmentHeader .= $returnArray[$i]. "n";   
}   
}  return $outAttachmentHeader;  
}   
/******************************   
函數 send()用於傳送郵件,傳送成功回傳值為true  
  ************************************/   
function send(){   
//--設定郵件頭為空   
$mailHeader = "";   
//--新增抄送人
if($this->mailCC != "")  
$mailHeader .= "CC: ".$this->mailCC. "n";   
//--新增秘密抄送人   
if($this->mailBCC != "")  
$mailHeader .= "BCC: ".$this->mailBCC. "n";  
//--新增寄件者
if($this->mailFrom != "")  
$mailHeader .= "FROM: ".$this->mailFrom. "n";  
//---------------------------郵件格式------------------- -----------  
//--文字格式
if($this->mailText != "" && $this->mailHTML == "" && $this->mailAttachments == ""){
return mail($this->mailTo,$this->mailSubject,$this->mailText,$mailHeader);  
}   
//--html或text格式  
else if($this->mailText != "" && $this->mailHTML != "" && $this->mailAttachments == ""){
$bodyBoundary = $this->getRandomBoundary();
$textHeader = $this->formatTextHeader();  
$htmlHeader = $this->formatHTMLHeader();  
//--設定 MIME-版本  
$mailHeader .= "MIME-Version: 1.0n";  
$mailHeader .= "Content-Type: multipart/alternative;n";
  $mailHeader .= ' boundary="'.$bodyBoundary. '"';  
$mailHeader .= "nnn";  
//--新增郵件主體和邊界  
$mailHeader .= "--".$bodyBoundary. "n";  
$mailHeader .= $textHeader;   
$mailHeader .= "--".$bodyBoundary. "n";  
//--新增html標籤   
$mailHeader .= $htmlHeader;   
$mailHeader .= "n--".$bodyBoundary. "--";   
//--寄郵件   
return mail($this->mailTo,$this->mailSubject, "",$mailHeader);  
}   
//--文字加html加上附件   
else if($this->mailText != "" && $this->mailHTML != "" && $this->mailAttachments != ""){
$attachmentBoundary = $this->getRandomBoundary();
   $mailHeader .= "Content-Type: multipart/mixed;n";  
$mailHeader .= ' boundary="'.$attachmentBoundary. '"'. "nn";  
$mailHeader .= "This is a multi-part message in MIME format.n";
  $mailHeader .= "--".$attachmentBoundary. "n";  
  $bodyBoundary = $this->getRandomBoundary(1);  
  $textHeader = $this->formatTextHeader();  
$htmlHeader = $this->formatHTMLHeader();  
$mailHeader .= "MIME-Version: 1.0n";  
  $mailHeader .= "Content-Type: multipart/alternative;n";  
$mailHeader .= ' boundary="'.$bodyBoundary. '"';  
$mailHeader .= "nnn";  
  $mailHeader .= "--".$bodyBoundary. "n";  
$mailHeader .= $textHeader;  
$mailHeader .= "--".$bodyBoundary. "n";  
  $mailHeader .= $htmlHeader;  
$mailHeader .= "n--".$bodyBoundary. "--";   
//--取得附件值  
$attachmentArray = explode( ",",$this->mailAttachments);   
//--依照附件的個數進行循環  
for($i=0;$i //--分割  $mailHeader .= "n--".$attachmentBoundary. "n";  
//--附件資訊  
$mailHeader .= $this->formatAttachmentHeader($attachmentArray[$i]);
  }   
$mailHeader .= "--".$attachmentBoundary. "--";   
return mail($this->mailTo,$this->mailSubject, "",$mailHeader);
  }   
return false;   
}   
}   
?>  


使用方法:

Include “email.class”

$mail->setTo("a@a.com"); //收件者  
$mail-> setCC("b@b.com,c@c.com"); //抄送
$mail-> setCC("d@b.com,e@c.com"); //秘密抄送
$mail->setFrom(“f@f.com”);//寄件者   
$mail->setSubject(“主題”) ; //主題
$mail->setText(“文字格式”)  ;//傳送文字格式也可以是變數
$mail->setHTML(“html格式”)  ;//傳送html格式也可以是變數
$mail->setAttachments(“c:a.jpg”) ;//新增附件,需表明路徑
$mail->send(); //傳送郵件 

以上就介紹了PHP的發送郵件類,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
高流量網站的PHP性能調整高流量網站的PHP性能調整May 14, 2025 am 12:13 AM

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

PHP中的依賴注入:初學者的代碼示例PHP中的依賴注入:初學者的代碼示例May 14, 2025 am 12:08 AM

你應該關心DependencyInjection(DI),因為它能讓你的代碼更清晰、更易維護。 1)DI通過解耦類,使其更模塊化,2)提高了測試的便捷性和代碼的靈活性,3)使用DI容器可以管理複雜的依賴關係,但要注意性能影響和循環依賴問題,4)最佳實踐是依賴於抽象接口,實現鬆散耦合。

PHP性能:是否可以優化應用程序?PHP性能:是否可以優化應用程序?May 14, 2025 am 12:04 AM

是的,優化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)優化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,並避免使用

PHP性能優化:最終指南PHP性能優化:最終指南May 14, 2025 am 12:02 AM

theKeyStrategiestosigantificallyBoostPhpaPplicationPerformenCeare:1)UseOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)優化AtabaseInteractionswithPreparedStateTementStatementStatementAndProperIndexing,3)配置

PHP依賴注入容器:快速啟動PHP依賴注入容器:快速啟動May 13, 2025 am 12:11 AM

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增強codemodocultion,可驗證性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

PHP中的依賴注入與服務定位器PHP中的依賴注入與服務定位器May 13, 2025 am 12:10 AM

選擇DependencyInjection(DI)用於大型應用,ServiceLocator適合小型項目或原型。 1)DI通過構造函數注入依賴,提高代碼的測試性和模塊化。 2)ServiceLocator通過中心註冊獲取服務,方便但可能導致代碼耦合度增加。

PHP性能優化策略。PHP性能優化策略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)啟用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替換loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

PHP電子郵件驗證:確保正確發送電子郵件PHP電子郵件驗證:確保正確發送電子郵件May 13, 2025 am 12:06 AM

phpemailvalidation invoLvesthreesteps:1)格式化進行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

See all articles

熱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

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

熱門文章

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

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

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用