搜索
首页后端开发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
在Laravel中使用Flash会话数据在Laravel中使用Flash会话数据Mar 12, 2025 pm 05:08 PM

Laravel使用其直观的闪存方法简化了处理临时会话数据。这非常适合在您的应用程序中显示简短的消息,警报或通知。 默认情况下,数据仅针对后续请求: $请求 -

PHP记录:PHP日志分析的最佳实践PHP记录:PHP日志分析的最佳实践Mar 10, 2025 pm 02:32 PM

PHP日志记录对于监视和调试Web应用程序以及捕获关键事件,错误和运行时行为至关重要。它为系统性能提供了宝贵的见解,有助于识别问题并支持更快的故障排除

php中的卷曲:如何在REST API中使用PHP卷曲扩展php中的卷曲:如何在REST API中使用PHP卷曲扩展Mar 14, 2025 am 11:42 AM

PHP客户端URL(curl)扩展是开发人员的强大工具,可以与远程服务器和REST API无缝交互。通过利用Libcurl(备受尊敬的多协议文件传输库),PHP curl促进了有效的执行

简化的HTTP响应在Laravel测试中模拟了简化的HTTP响应在Laravel测试中模拟了Mar 12, 2025 pm 05:09 PM

Laravel 提供简洁的 HTTP 响应模拟语法,简化了 HTTP 交互测试。这种方法显着减少了代码冗余,同时使您的测试模拟更直观。 基本实现提供了多种响应类型快捷方式: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

在Codecanyon上的12个最佳PHP聊天脚本在Codecanyon上的12个最佳PHP聊天脚本Mar 13, 2025 pm 12:08 PM

您是否想为客户最紧迫的问题提供实时的即时解决方案? 实时聊天使您可以与客户进行实时对话,并立即解决他们的问题。它允许您为您的自定义提供更快的服务

解释PHP中晚期静态结合的概念。解释PHP中晚期静态结合的概念。Mar 21, 2025 pm 01:33 PM

文章讨论了PHP 5.3中引入的PHP中的晚期静态结合(LSB),从而允许静态方法的运行时分辨率调用以获得更灵活的继承。 LSB的实用应用和潜在的触摸

自定义/扩展框架:如何添加自定义功能。自定义/扩展框架:如何添加自定义功能。Mar 28, 2025 pm 05:12 PM

本文讨论了将自定义功能添加到框架上,专注于理解体系结构,识别扩展点以及集成和调试的最佳实践。

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脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

mPDF

mPDF

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

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

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

禅工作室 13.0.1

禅工作室 13.0.1

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