搜索
首页后端开发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
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)

如何使PHP应用程序更快如何使PHP应用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,关注台词:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能优化清单:立即提高速度PHP性能优化清单:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,关注台词:1)启用opcodeCachingwithapCutoredUcescriptexecutiontime.2)实现databasequerycachingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandredececonnection.4 limitsclection.4.4

PHP依赖注入:提高代码可检验性PHP依赖注入:提高代码可检验性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显着提升了PHP代码的可测试性。 1)DI解耦类与具体实现,使测试和维护更灵活。 2)三种类型中,构造函数注入明确表达依赖,保持状态一致。 3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能优化:数据库查询优化PHP性能优化:数据库查询优化May 12, 2025 am 12:02 AM

databasequeryOptimizationinphpinvolVolVOLVESEVERSEVERSTRATEMIESOENHANCEPERANCE.1)SELECTONLYNLYNESSERSAYCOLUMNSTORMONTOUMTOUNSOUDSATATATATATATATATATATRANSFER.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

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

热门文章

热工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具