轻量级PHP邮件发送,需要有smtp服务器,代码经过多次实战使用,现在把代码分享给大家
复制代码 代码如下:
/*
邮件发送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==''){
$this->error('请配置好邮件登录用户名!');
return false;
}
if($this->mailPwd==''){
$this->error('请配置好邮件登录密码!');
return false;
}
if($this->server==''){
$this->error('请配置好邮服务器地址!');
return false;
}
if(!is_numeric($this->port)){
$this->error('请配置好邮服务器端口!');
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 == '1'){
$resp = $resp && $this->login();
}
if(!$resp){
$this->failed = true;
}
}
/*
发送邮件
@param string $to 接收邮件地址
@param string $msg 邮件主要内容
@title string $title 邮件标题
*/
public function sendMail($to,$msg,$title=''){
if($msg=='' ){
return false;
}
if(is_array($to)){
if($to!=null){
foreach($to as $k=>$e){
if(!preg_match('/^[a-z0-9A-Z_-]+@+([a-z0-9A-Z_-]+\.)+[a-z0-9A-Z]{2,3}$/',$e)){
unset($to[$k]);
}
}
}else{
return false;
}
if($to == null){
return false;
}
}else{
if(!preg_match('/^[a-z0-9A-Z_-]+@+([a-z0-9A-Z_-]+\.)+[a-z0-9A-Z]{2,3}$/',$to)){
return false;
}
}
if(!self::$smtpCon){
return false;
}
$this->sendSmtpMsg('MAIL FROM:senderMail.'>');
if(!is_array($to)){
$this->sendSmtpMsg('RCPT TO:');
}else{
foreach($to as $k=>$email){
$this->sendSmtpMsg('RCPT TO:');
}
}
$this->sendSmtpMsg("DATA");
if($this->status !='354'){
$this->error('请求发送邮件失败!');
$this->failed = true;
return false;
}
$msg = base64_encode($msg);
$msg = str_replace($this->stop . '.', $this->stop . '..', $msg);
$msg = substr($msg, 0, 1) == '.' ? '.' . $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('',false);
$this->sendSmtpMsg($msg,false);
}
$this->sendSmtpMsg('.');//发送结束标识符
if($this->status != '250'){
$this->failed = true;
$this->error($this->readSmtpMsg());
return false;
}
return true;
}
/*
关闭邮件连接
*/
public function close(){
$this->sendSmtpMsg('Quite');
@socket_close(self::$smtpCon);
}
/*
添加普通邮件头信息
*/
protected function mailHeader($to,$title){
$headers = array();
$headers[] = 'Date: '.$this->gmtime('D j M Y H:i:s').' '.date('O');
if(!is_array($to)){
$headers[] = 'To: "'.'=?'.$this->charset.'?B?'.base64_encode($this->getMailUser($to)).'?="';
}else{
foreach($to as $k=>$e){
$headers[] = 'To: "'.'=?'.$this->charset.'?B?'.base64_encode($this->getMailUser($e)).'?="';
}
}
$headers[] = 'From: "=?'.$this->charset.'?B?'.base64_encode($this->senderName).'?="senderMail.'>';
$headers[] = 'Subject: =?'.$this->charset.'?B?'.base64_encode($title).'?=';
$headers[] = 'Content-type: text/html; charset='.$this->charset.'; format=flowed';
$headers[] = 'Content-Transfer-Encoding: base64';
$headers = str_replace($this->stop . '.', $this->stop . '..', trim(implode($this->stop, $headers)));
return $headers;
}
/*
带付件的头部信息
*/
protected function mimeHeader($msg,$to,$title){
if($this->attachMent!=null){
$headers = array();
$boundary = '----='.uniqid();
$headers[] = 'Date: '.$this->gmtime('D j M Y H:i:s').' '.date('O');
if(!is_array($to)){
$headers[] = 'To: "'.'=?'.$this->charset.'?B?'.base64_encode($this->getMailUser($to)).'?="';
}else{
foreach($to as $k=>$e){
$headers[] = 'To: "'.'=?'.$this->charset.'?B?'.base64_encode($this->getMailUser($e)).'?="';
}
}
$headers[] = 'From: "=?'.$this->charset.'?B?'.base64_encode($this->senderName).'?="senderMail.'>';
$headers[] = 'Subject: =?'.$this->charset.'?B?'.base64_encode($title).'?=';
$headers[] = 'Mime-Version: 1.0';
$headers[] = 'Content-Type: multipart/mixed;boundary="'.$boundary.'"'.$this->stop;
$headers[]='--'.$boundary;
$headers[]='Content-Type: text/html;charset="'.$this->charset.'"';
$headers[]='Content-Transfer-Encoding: base64'.$this->stop;
$headers[] = '';
$headers[]= $msg.$this->stop;
foreach($this->attachMent as $k=>$filename){
$f = @fopen($filename, 'r');
$mimetype = $this->getMimeType(realpath($filename));
$mimetype = $mimetype == '' ? 'application/octet-stream' : $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)).'?="' ;
$headers[] = "Content-disposition: attachment; name=\"=?".$this->charset."?B?". base64_encode(basename($filename)).'?="';
$headers[] = 'Content-Transfer-Encoding: base64'.$this->stop;
$headers[] = $attachment.$this->stop;
}
$headers[] = "--" . $boundary . "--";
$headers = str_replace($this->stop . '.', $this->stop . '..', 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 = '';
$line = '';
while (strpos($return, $this->stop)=== false OR $line{3}!== ' ')
{
$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('Z'));
}
/*
获取付件的mime类型
*/
protected function getMimeType($file){
$mimes = array(
'chm'=>'application/octet-stream', 'ppt'=>'application/vnd.ms-powerpoint',
'xls'=>'application/vnd.ms-excel', 'doc'=>'application/msword', 'exe'=>'application/octet-stream',
'rar'=>'application/octet-stream', 'js'=>"javascrīpt/js", 'css'=>"text/css",
'hqx'=>"application/mac-binhex40", 'bin'=>"application/octet-stream", 'oda'=>"application/oda", 'pdf'=>"application/pdf",
'ai'=>"application/postsrcipt", 'eps'=>"application/postsrcipt", 'es'=>"application/postsrcipt", 'rtf'=>"application/rtf",
'mif'=>"application/x-mif", 'csh'=>"application/x-csh", 'dvi'=>"application/x-dvi", 'hdf'=>"application/x-hdf",
'nc'=>"application/x-netcdf", 'cdf'=>"application/x-netcdf", 'latex'=>"application/x-latex", 'ts'=>"application/x-troll-ts",
'src'=>"application/x-wais-source", 'zip'=>"application/zip", 'bcpio'=>"application/x-bcpio", 'cpio'=>"application/x-cpio",
'gtar'=>"application/x-gtar", 'shar'=>"application/x-shar", 'sv4cpio'=>"application/x-sv4cpio", 'sv4crc'=>"application/x-sv4crc",
'tar'=>"application/x-tar",'ustar'=>"application/x-ustar",'man'=>"application/x-troff-man", 'sh'=>"application/x-sh",
'tcl'=>"application/x-tcl", 'tex'=>"application/x-tex", 'texi'=>"application/x-texinfo",'texinfo'=>"application/x-texinfo",
't'=>"application/x-troff", 'tr'=>"application/x-troff", 'roff'=>"application/x-troff",
'shar'=>"application/x-shar", 'me'=>"application/x-troll-me", 'ts'=>"application/x-troll-ts",
'gif'=>"image/gif", 'jpeg'=>"image/pjpeg", 'jpg'=>"image/pjpeg", 'jpe'=>"image/pjpeg", 'ras'=>"image/x-cmu-raster",
'pbm'=>"image/x-portable-bitmap", 'ppm'=>"image/x-portable-pixmap", 'xbm'=>"image/x-xbitmap", 'xwd'=>"image/x-xwindowdump",
'ief'=>"image/ief", 'tif'=>"image/tiff", 'tiff'=>"image/tiff", 'pnm'=>"image/x-portable-anymap", 'pgm'=>"image/x-portable-graymap",
'rgb'=>"image/x-rgb", 'xpm'=>"image/x-xpixmap", 'txt'=>"text/plain", 'c'=>"text/plain", 'cc'=>"text/plain",
'h'=>"text/plain", 'html'=>"text/html", 'htm'=>"text/html", 'htl'=>"text/html", 'rtx'=>"text/richtext", 'etx'=>"text/x-setext",
'tsv'=>"text/tab-separated-values", 'mpeg'=>"video/mpeg", 'mpg'=>"video/mpeg", 'mpe'=>"video/mpeg", 'avi'=>"video/x-msvideo",
'qt'=>"video/quicktime", 'mov'=>"video/quicktime", 'moov'=>"video/quicktime", 'movie'=>"video/x-sgi-movie", 'au'=>"audio/basic",
'snd'=>"audio/basic", 'wav'=>"audio/x-wav", 'aif'=>"audio/x-aiff", 'aiff'=>"audio/x-aiff", 'aifc'=>"audio/x-aiff",
'swf'=>"application/x-shockwave-flash", 'myz'=>"application/myz"
);
$ext = substr(strrchr($file,'.'),1);
$type = $mimes[$ext];
unset($mimes);
return $type;
}
/*
邮件helo命令
*/
private function helo(){
if($this->status != '220'){
$this->error('连接服务器失败!');
return false;
}
return $this->sendSmtpMsg('HELO '.$this->server);
}
/*
登录
*/
private function login(){
if($this->status!='250'){
$this->error('helo邮件指令失败!');
return false;
}
$this->sendSmtpMsg('AUTH LOGIN');
if($this->status!='334'){
$this->error('AUTH LOGIN 邮件指令失败!');
return false;
}
$this->sendSmtpMsg(base64_encode($this->mailUser));
if($this->status!='334'){
$this->error('邮件登录用户名可能不正确!'.$this->readSmtpMsg());
return false;
}
$this->sendSmtpMsg(base64_encode($this->mailPwd));
if($this->status !='235'){
$this->error('邮件登录密码可能不正确!');
return false;
}
return true;
}
private function getMailUser($to){
$temp = explode('@',$to);
return $temp[0];
}
/*
异常报告
*/
private function error($exception){
if($this->showError == false){
file_put_contents('mail_log.txt',$exception,FILE_APPEND);
return;
}
if(class_exists('error') && is_object($GLOBALS['error'])){
$GLOBALS['error']->showErrorStr($exception,'javascript:',false);
}else{
throw new Exception($exception);
}
}
}
// 使用示例
ini_set('memory_limit','128M');
set_time_limit(120);
define('MAIL_SENDER_NAME','楚贤');
define('MAIL_SMTP_HOST','smtp.ym.163.com');
define('MAIL_USER','admin@myxxxx.com');
define('MAIL_SENDER','admin@myxxxx.com');
define('MAIL_PWD','xxxx');
define('MAIL_SMTP_PORT',25);
define('IN_SSL',false);
define('MAIL_TIMEOUT',10);
define('MAIL_CHARSET','utf-8');
date_default_timezone_set('PRC');
$m = new smtp();
$msg = "有用户登录服务器@".date('Y-m-d H:i:s');
付件
//$m->attachMent = array('hehe.php','common.php');
if($m->sendMail(array('610269963@qq.com'),$msg,'88服务器登录提示')){
echo '发送成功!';
}
$m->close();
?>

PHPSession失效的原因包括配置錯誤、Cookie問題和Session過期。 1.配置錯誤:檢查並設置正確的session.save_path。 2.Cookie問題:確保Cookie設置正確。 3.Session過期:調整session.gc_maxlifetime值以延長會話時間。

在PHP中調試會話問題的方法包括:1.檢查會話是否正確啟動;2.驗證會話ID的傳遞;3.檢查會話數據的存儲和讀取;4.查看服務器配置。通過輸出會話ID和數據、查看會話文件內容等方法,可以有效診斷和解決會話相關的問題。

多次調用session_start()會導致警告信息和可能的數據覆蓋。 1)PHP會發出警告,提示session已啟動。 2)可能導致session數據意外覆蓋。 3)使用session_status()檢查session狀態,避免重複調用。

在PHP中配置會話生命週期可以通過設置session.gc_maxlifetime和session.cookie_lifetime來實現。 1)session.gc_maxlifetime控制服務器端會話數據的存活時間,2)session.cookie_lifetime控制客戶端cookie的生命週期,設置為0時cookie在瀏覽器關閉時過期。

使用數據庫存儲會話的主要優勢包括持久性、可擴展性和安全性。 1.持久性:即使服務器重啟,會話數據也能保持不變。 2.可擴展性:適用於分佈式系統,確保會話數據在多服務器間同步。 3.安全性:數據庫提供加密存儲,保護敏感信息。

在PHP中實現自定義會話處理可以通過實現SessionHandlerInterface接口來完成。具體步驟包括:1)創建實現SessionHandlerInterface的類,如CustomSessionHandler;2)重寫接口中的方法(如open,close,read,write,destroy,gc)來定義會話數據的生命週期和存儲方式;3)在PHP腳本中註冊自定義會話處理器並啟動會話。這樣可以將數據存儲在MySQL、Redis等介質中,提升性能、安全性和可擴展性。

SessionID是網絡應用程序中用來跟踪用戶會話狀態的機制。 1.它是一個隨機生成的字符串,用於在用戶與服務器之間的多次交互中保持用戶的身份信息。 2.服務器生成並通過cookie或URL參數發送給客戶端,幫助在用戶的多次請求中識別和關聯這些請求。 3.生成通常使用隨機算法保證唯一性和不可預測性。 4.在實際開發中,可以使用內存數據庫如Redis來存儲session數據,提升性能和安全性。

在無狀態環境如API中管理會話可以通過使用JWT或cookies來實現。 1.JWT適合無狀態和可擴展性,但大數據時體積大。 2.Cookies更傳統且易實現,但需謹慎配置以確保安全性。


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Linux新版
SublimeText3 Linux最新版

記事本++7.3.1
好用且免費的程式碼編輯器

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中