ホームページ  >  記事  >  バックエンド開発  >  PHPでsmtpを使用して添付ファイルをサポートするメールを送信する方法

PHPでsmtpを使用して添付ファイルをサポートするメールを送信する方法

不言
不言オリジナル
2018-06-13 14:25:532934ブラウズ

この記事では主に、PHP で添付ファイルをサポートするメールを送信するために smtp を使用する例を紹介します。このコードは、多くの実用的なアプリケーションで使用されています。

Lightweight を参照してください。 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 中国語 Web サイトに注目してください。

関連する推奨事項:

laravel sms を使用して、検証用の SMS 確認コードを送信する機能を構築する

PHP の致命的エラー session_start() エラーの解決方法

PHP の autoLoad 自動読み込み機構の分析

#

以上がPHPでsmtpを使用して添付ファイルをサポートするメールを送信する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。