搜索
首页后端开发php教程php使用smtp发送支持附件的邮件示例_PHP

轻量级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 ="rn";
 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());
   返回 false;
  }

  return true;
 }

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

  $this->sendSmtpMsg('Quite');
  @socket_close(self::$smtpCon);
 }

 /*
 添加普通邮件头信息
 * /
 受保护的函数 mailHeader($to,$title){
  $headers = array();
  $headers[] = '日期:'.$this->gmtime('D j M Y H:是')。' '.date('O');

  if(!is_array($to)){
   $headers[] = 'To: "'.'=?'.$this-> 字符集.'?B?'.base64_encode($this->getMailUser($to)).'?="';
  }else{
   foreach($to as $k=>$e){
    $headers[] = '收件人: "'.'=?'.$this->字符集.'?B?'.base64_encode($this->getMailUser ($e)).'?="';
   }
  }

  $headers[] = '来自:"=?'.$ this->charset.'?B?'.base64_encode($this->senderName).'?="senderMail.'>';
  $headers[] = '主题:=?'.$this->字符集。'?B?'.base64_encode($title).'?=';
  $headers[] = '内容类型:text/html;字符集='.$this->字符集。';格式=流动';
  $headers[] = '内容传输编码: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[] = '日期:'.$this->gmtime('D j M Y H:i:s').' '.date('O'); 
   if(!is_array($to)){
    $headers[] = 'To: "'.'=?'.$this->字符集.'?B?'.base64_encode($this- >getMailUser($to)).'?="';
   }else{
    foreach($to as $k=>$e){
     $headers[] = '收件人:"'.'=?'.$this->字符集.'?B?'.base64_encode($this->getMailUser($e)).'?="';
    }
   }

   $headers[] = '来自:"=?'.$this->字符集.'?B?'.base64_encode($this->senderName).'?="senderMail.'>';
   $headers[] = '主题:=?'.$this->字符集.'?B?'.base64_encode($title).'?=' ;
   $headers[] =  'Mime 版本:1.0';
   $headers[] = '内容类型:multipart/mixed;boundary="'.$boundary.'"'.$this-> ;stop;
   $headers[]='--'.$boundary;

   $headers[]='Content-Type: text/html;charset="'.$this->charset .'"';
   $headers[]='内容传输编码: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[] = "内容类型:".$mimetype.";name="=?".$this->字符集。"?B?".base64_encode(basename($filename) ).'?="' ;
    $headers[] = "内容处置: 附件; name="=?".$this-> 字符集."?B?". ).'?="';
    $headers[] = '内容传输编码:base64'.$this->stop;
    $headers[] = $attachment.$this->stop ;

   

   }
   $headers[] = "--" . $边界。 "--";
   $headers = str_replace($this->stop . '.', $this->stop . '..', trim(implode($this->stop, $headers) ));
   return $headers;

  } 
 }

 /*
 获取返回状态
 */
 受保护函数 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 或 $line{ 3}!== ' ')
  {
   $line    = fgets(self::$smtpCon, 512);
   $return .= $line;
  }

  return修剪($返回); 

 }

 /*
 给邮件服务器发送指定命令消息
 */
 受保护函数 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;
 }

 /*
邮件时间格式
 */
 受保护函数 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'=>"应用程序/x-dvi", 'hdf'=>"应用程序/x-hdf",
   'nc'=>"应用程序/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'=>"应用程序/x-gtar"、'shar'=>"应用程序/x-shar"、'sv4cpio'=>"应用程序/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 '=>"图像/pjpeg", 'jpe'=>"图像/pjpeg", 'ras'=>"图像/x-cmu-raster",
   'pbm'=>"图像/ x-portable-bitmap", 'ppm'=>"图像/x-portable-pixmap", 'xbm'=>"图像/x-xbitmap", 'xwd'=>"图像/x-xwindowdump" ,
   'ief'=>"图像/ief", 'tif'=>"图像/tiff", 'tiff'=>"图像/tiff", 'pnm'=>"图像/x -portable-anymap", 'pgm'=>"image/x-portable-graymap",
   'rgb'=>"image/x-rgb", 'xpm'=>"image/x- xpixmap", 'txt'=>"文本/纯文本", 'c'=>"文本/纯文本", 'cc'=>"文本/纯文本",
   'h'=>"文本/plain", 'html'=>"text/html", 'htm'=>"text/html", 'htl'=>"text/html", 'rtx'=>"text/richtext ", 'etx'=>"text/x-setext",
   'tsv'=>"文本/制表符分隔值", 'mpeg'=>"视频/mpeg", 'mpg' =>"视频/mpeg", 'mpe'=>"视频/mpeg", 'avi'=>"视频/x-msvideo",
   'qt'=>"视频/quicktime", 'mov'=>"视频/quicktime", 'moov'=>"视频/quicktime", 'movie'=>"视频/x-sgi-movie", 'au'=>"音频/基本",
   'snd'=>"音频/基本", 'wav'=>"音频/x-wav", 'aif'=>"音频/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;
 }

 /*
 mailhelo命令
 */
 私有函数 helo(){

  if($this->status != '220'){

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

  return $this->sendSmtpMsg('HELO '.$this->server);

 }

 
 /*
 登录
 */
 私有函数login(){

  if($this->status!='250'){

   $ this->error('heloMail 指令失败!');
   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());
   返回 false;
  }

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

  return true;

 }

 私有函数 getMailUser($ to){

  $temp =explode('@',$to);
  return $temp[0];
 }
 /*
 异常报告
 * /
 私有函数错误($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($异常,'javascript:',false);
  }else{
   抛出新的异常($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- >关闭();
?>

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
哪些常见问题会导致PHP会话失败?哪些常见问题会导致PHP会话失败?Apr 25, 2025 am 12:16 AM

PHPSession失效的原因包括配置错误、Cookie问题和Session过期。1.配置错误:检查并设置正确的session.save_path。2.Cookie问题:确保Cookie设置正确。3.Session过期:调整session.gc_maxlifetime值以延长会话时间。

您如何在PHP中调试与会话相关的问题?您如何在PHP中调试与会话相关的问题?Apr 25, 2025 am 12:12 AM

在PHP中调试会话问题的方法包括:1.检查会话是否正确启动;2.验证会话ID的传递;3.检查会话数据的存储和读取;4.查看服务器配置。通过输出会话ID和数据、查看会话文件内容等方法,可以有效诊断和解决会话相关的问题。

如果session_start()被多次调用会发生什么?如果session_start()被多次调用会发生什么?Apr 25, 2025 am 12:06 AM

多次调用session_start()会导致警告信息和可能的数据覆盖。1)PHP会发出警告,提示session已启动。2)可能导致session数据意外覆盖。3)使用session_status()检查session状态,避免重复调用。

您如何在PHP中配置会话寿命?您如何在PHP中配置会话寿命?Apr 25, 2025 am 12:05 AM

在PHP中配置会话生命周期可以通过设置session.gc_maxlifetime和session.cookie_lifetime来实现。1)session.gc_maxlifetime控制服务器端会话数据的存活时间,2)session.cookie_lifetime控制客户端cookie的生命周期,设置为0时cookie在浏览器关闭时过期。

使用数据库存储会话的优点是什么?使用数据库存储会话的优点是什么?Apr 24, 2025 am 12:16 AM

使用数据库存储会话的主要优势包括持久性、可扩展性和安全性。1.持久性:即使服务器重启,会话数据也能保持不变。2.可扩展性:适用于分布式系统,确保会话数据在多服务器间同步。3.安全性:数据库提供加密存储,保护敏感信息。

您如何在PHP中实现自定义会话处理?您如何在PHP中实现自定义会话处理?Apr 24, 2025 am 12:16 AM

在PHP中实现自定义会话处理可以通过实现SessionHandlerInterface接口来完成。具体步骤包括:1)创建实现SessionHandlerInterface的类,如CustomSessionHandler;2)重写接口中的方法(如open,close,read,write,destroy,gc)来定义会话数据的生命周期和存储方式;3)在PHP脚本中注册自定义会话处理器并启动会话。这样可以将数据存储在MySQL、Redis等介质中,提升性能、安全性和可扩展性。

什么是会话ID?什么是会话ID?Apr 24, 2025 am 12:13 AM

SessionID是网络应用程序中用来跟踪用户会话状态的机制。1.它是一个随机生成的字符串,用于在用户与服务器之间的多次交互中保持用户的身份信息。2.服务器生成并通过cookie或URL参数发送给客户端,帮助在用户的多次请求中识别和关联这些请求。3.生成通常使用随机算法保证唯一性和不可预测性。4.在实际开发中,可以使用内存数据库如Redis来存储session数据,提升性能和安全性。

您如何在无状态环境(例如API)中处理会议?您如何在无状态环境(例如API)中处理会议?Apr 24, 2025 am 12:12 AM

在无状态环境如API中管理会话可以通过使用JWT或cookies来实现。1.JWT适合无状态和可扩展性,但大数据时体积大。2.Cookies更传统且易实现,但需谨慎配置以确保安全性。

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

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境