欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php使用smtp发送支持附件的邮件示例

程序员文章站 2022-06-20 22:39:04
轻量级php邮件发送,需要有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==''){
   $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:<'.$this->sendermail.'>');

  if(!is_array($to)){     
   $this->sendsmtpmsg('rcpt to:<'.$to.'>');
  }else{

   foreach($to as $k=>$email){   
    $this->sendsmtpmsg('rcpt to:<'.$email.'>');
   }
  }

  $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)).'?="<'.$to.'>';
  }else{
   foreach($to as $k=>$e){
    $headers[] = 'to: "'.'=?'.$this->charset.'?b?'.base64_encode($this->getmailuser($e)).'?="<'.$e.'>';
   }
  }

  $headers[] = 'from: "=?'.$this->charset.'?b?'.base64_encode($this->sendername).'?="<'.$this->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)).'?="<'.$to.'>';
   }else{
    foreach($to as $k=>$e){
     $headers[] = 'to: "'.'=?'.$this->charset.'?b?'.base64_encode($this->getmailuser($e)).'?="<'.$e.'>';
    }
   }

   $headers[] = 'from: "=?'.$this->charset.'?b?'.base64_encode($this->sendername).'?="<'.$this->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();
?>