搜索
首页后端开发php教程php:smtp方式或mail函数方式发送邮件

php实现的邮件发送类,二种方式:
smtp方式与mail函数方式。

代码:

<?php 
/**
* 邮件发送类
*/
Class sendmail{ 
    public $smtp_host; 
    public $smtp_port = 25; 
    public $smtp_user; 
    public $smtp_password; 
    public $from_name; 
    public $SendFromMail; 
    public $mail_to; 
    public $subject; 
    public $message; 
    public $headers = &#39;&#39;; 
    public $ContentType = &#39;html&#39;; 
    public $charset = &#39;windows-1251&#39;; 
    public $smtp_debug = true; 
    public $socket; 
    public $error; 
    public $SendMailVia  = &#39;smtp&#39;; 
     
  public function construct() 
    { 
            if($this->SendFromMail == &#39;&#39;){ 
               $this->SendFromMail = $this->smtp_user; 
            } 
    } 
     
    public function Send($mail_to = &#39;&#39;, $subject = &#39;&#39;, $message = &#39;&#39;) 
    { 
        if($mail_to!=&#39;&#39;){$this->mail_to = stripslashes($mail_to);} 
            if($subject!=&#39;&#39;){$this->subject = stripslashes($subject);} 
            if($message!=&#39;&#39;){$this->message = $message;} 
            $meilsArr = array_filter($this->GetMailAndNameArr()); 
            if(trim($this->mail_to)==&#39;&#39;){$this->error = &#39;Enter the recipient address&#39;; } 
            if($meilsArr == array()){$this->error = &#39;Please enter a valid recipient address&#39;; } 
            foreach ($meilsArr as $val) 
            { 
                $validEmail = $this->validEmail($val[2]); 
                if($validEmail) 
                { 
                  if($this->SendMailVia==&#39;smtp&#39;){ 
                      return $this->SMTPsend($mail_to = $val[2], $name_to = $val[1]); 
                    } 
                    else{ 
                      return $this->MAILsend($mail_to = $val[2], $name_to = $val[1]); 
                    }     
                } 
            } 
    } 
     
    public function MAILsend($mail_to, $name_to) 
    { 
    if($this->ContentType=="text"){ 
        $header="Content-Type: text/plain; charset=".$this->charset.""; 
      } 
        else{ 
        $header="Return-Path: ".$this->smtp_user."\n". 
      "Reply-To: ".$this->SendFromMail."\n". 
      "From: ".$this->from_name." <".$this->SendFromMail.">\n". 
      "Subject: ".$this->subject."\n". 
        "Content-Type: text/html; charset=".$this->charset."\n"; 
      } 
      if(mail("$name_to <$mail_to>",$this->subject,$this->message,$header)){ 
         return true; 
        }else{ 
         return false; 
        } 
  } 
     
    public function SMTPsend($mail_to, $name_to) 
    { 
            $SEND =   "Date: ".date("D, d M Y H:i:s") . "\r\n"; 
            $SEND .=   &#39;Subject: =?&#39;.$this->charset.&#39;?B?&#39;.base64_encode($this->subject)."=?=\r\n"; 
            if ($this->headers!=&#39;&#39;){ $SEND .= $this->headers."\r\n\r\n"; } 
      else 
      { 
         $SEND .= "Reply-To: ".$this->SendFromMail."\r\n"; 
         $SEND .= "MIME-Version: 1.0\r\n"; 
         $SEND .= "Content-Type: text/".$this->ContentType."; charset=\"".$this->charset."\"\r\n"; 
         $SEND .= "Content-Transfer-Encoding: 8bit\r\n"; 
         $SEND .= "From: \"".$this->from_name."\" <".$this->SendFromMail.">\r\n"; 
         $SEND .= "To: $name_to <$mail_to>\r\n"; 
         $SEND .= "X-Priority: 3\r\n\r\n"; 
      } 
      $SEND .=  $this->message."\r\n"; 
         
                $socket = fsockopen($this->smtp_host, $this->smtp_port, $errno, $errstr, 30); 
          if(!socket) 
            { 
          if($this->smtp_debug) $this->error = $errno." - ".$errstr; 
          return false; 
        } 
                 
                if (!$this->server_parse($socket, "220", LINE)){ return false; } 
                 
            fputs($socket, "HELO ".$this->smtp_host. "\r\n"); 
            if (!$this->server_parse($socket, "250", LINE)) { 
               if ($this->smtp_debug) $this->error = &#39;<p>Can not send HELO!</p>&#39;; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, "AUTH LOGIN\r\n"); 
            if (!$this->server_parse($socket, "334", LINE)) { 
               if ($this->smtp_debug) $this->error = &#39;<p>Can not find an answer to a request authorization.</p>&#39;; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, base64_encode($this->smtp_user) . "\r\n"); 
            if (!$this->server_parse($socket, "334", LINE)) { 
               if ($this->smtp_debug) $this->error = &#39;<p>Login authorization was not accepted by server!</p>&#39;; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, base64_encode($this->smtp_password) . "\r\n"); 
            if (!$this->server_parse($socket, "235", LINE)) { 
               if ($this->smtp_debug) $this->error = &#39;<p>No password was not accepted as a true server! Authorization Error!</p>&#39;; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, "MAIL FROM: <".$this->smtp_user.">\r\n"); 
            if (!$this->server_parse($socket, "250", LINE)) { 
               if ($this->smtp_debug) $this->error = &#39;<p>Unable to send command MAIL FROM: </p>&#39;; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, "RCPT TO: <" . $mail_to . ">\r\n"); 
            if (!$this->server_parse($socket, "250", LINE)) { 
               if ($this->smtp_debug) $this->error = &#39;<p>Unable to send command RCPT TO: </p>&#39;; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, "DATA\r\n"); 
            if (!$this->server_parse($socket, "354", LINE)) { 
               if ($this->smtp_debug) $this->error = &#39;<p>Unable to send command DATA</p>&#39;; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, $SEND."\r\n.\r\n"); 
            if (!$this->server_parse($socket, "250", LINE)) { 
               if ($this->smtp_debug) $this->error = &#39;<p>Unable to send the message body. The letter was sent!</p>&#39;; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, "QUIT\r\n"); 
            fclose($socket); 
            return TRUE; 
    } 
       
    private function GetMailAndNameArr(){ 
        $mailingArr = array(); 
            $tos = preg_split("/;|,/",$this->mail_to); 
            $pregcode = &#39;/(.*?)<(.*?)>/i&#39;; 
            foreach($tos as $to) 
            { 
              if(preg_match(&#39;/(.*?)<(.*?)>/i&#39;,$to,$matches)) 
                { 
                  unset($matches[0]);     
                  $matches[1] = trim(str_replace(&#39;"&#39;,&#39;&#39;,$matches[1])); 
                  $matches[2] = trim($matches[2]); 
                  $mailingArr[] =$matches;  
                } 
                elseif(preg_match(&#39;/\b([A-Z0-9._%-]+)@([A-Z0-9.-]+\.[A-Z]{2,4})\b/i&#39;,$to,$matches2)) 
                { 
                     unset($matches[0]);     
                     $matches[1] = trim(str_replace(&#39;"&#39;,&#39;&#39;,$matches2[1])); 
                     $matches[2] = trim($matches2[0]); 
                     $mailingArr[] =$matches; 
                } 
            } 
            return $mailingArr; 
    } 
     
    private function server_parse($socket, $response, $line = LINE) { 
    while (substr($server_response, 3, 1) != &#39; &#39;) { 
          if (!($server_response = fgets($socket, 256))) { 
               if ($this->smtp_debug) $this->error = "<p>$line Problems sending mail! $response</p>"; 
               return false; 
          } 
    } 
    if (!(substr($server_response, 0, 3) == $response)) { 
           if ($this->smtp_debug) $this->error = "<p>$line Problems sending mail! $response</p>"; 
           return false; 
        } 
    return true; 
  } 
  function validEmail($email) 
  { 
    $isValid = true; 
    $atIndex = strrpos($email, "@"); 
      $msg = &#39;&#39;; 
    if (is_bool($atIndex) && !$atIndex) 
    { 
      $isValid = false; 
    } 
    else 
    { 
      $domain = substr($email, $atIndex+1); 
      $local = substr($email, 0, $atIndex); 
      $localLen = strlen($local); 
      $domainLen = strlen($domain); 
      if ($localLen < 1 || $localLen > 64){ 
                 $msg = &#39;local part length exceeded&#39;; 
         $isValid = false; 
      } 
      else if ($domainLen < 1 || $domainLen > 255){ 
                 $msg = &#39; domain part length exceeded &#39;; 
         $isValid = false; 
      } 
      else if ($local[0] == &#39;.&#39; || $local[$localLen-1] == &#39;.&#39;){ 
                 $msg = &#39; local part starts or ends with .&#39;; 
         $isValid = false; 
      } 
      else if (preg_match(&#39;/\\.\\./&#39;, $local)){ 
                 $msg = &#39;local part has two consecutive dots&#39;; 
         $isValid = false; 
      } 
      else if (!preg_match(&#39;/^[A-Za-z0-9\\-\\.]+$/&#39;, $domain)){ 
                 $msg = &#39;character not valid in domain part&#39;; 
         $isValid = false; 
      } 
      else if (preg_match(&#39;/\\.\\./&#39;, $domain)){ 
                 $msg = &#39;  domain part has two consecutive dots&#39;; 
         $isValid = false; 
      } 
      else if(!preg_match(&#39;/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\&#39;*+?^{}|~.-])+$/&#39;, str_replace("\\\\","",$local))){ 
                 $msg = &#39;  character not valid in local part unless local part is quoted&#39;; 
         if (!preg_match(&#39;/^"(\\\\"|[^"])+"$/&#39;,str_replace("\\\\","",$local))){ 
            $isValid = false; 
         } 
      } 
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))){ 
                 $msg = &#39;  domain <b>&#39;.$domain.&#39;</b> not found in DNS&#39;; 
         $isValid = false; 
      } 
    } 
      $this->error = $msg; 
    return $isValid; 
  } 
} 
?>

调用示例:

<?php  
include "sendmail.class.php"; 
$Mail = new sendmail(); 
// Set congif 
$Mail->SendMailVia = &#39;smtp&#39;;  // Send via smtp server or mail function 
$Mail->smtp_host = &#39;mail.myhost.com&#39;; 
$Mail->smtp_port = 25; 
$Mail->smtp_user = &#39;user@myhost.com&#39;; 
$Mail->smtp_password = &#39;mypassw&#39;; 
// 例1 (mail from me) 
if($Mail->Send(&#39;mymail1@mydomain.com; recipient2 name <recipientmail2@mydomain.com>,"recipient name" <recipient@mail.com>&#39;,
&#39;My subject&#39;,&#39;My message here.&#39;)) 
{ 
  echo &#39;邮件已发送!&#39;; 
} 
else 
{ 
  echo $Mail->error; 
} 
// 例2 (mail from me) 
$Mail->mail_to = &#39;mymail1@mydomain.com; recipient2 name <recipientmail2@mydomain.com>,"recipient name" <recipient@mail.com>&#39;; 
$Mail->subject = &#39;My subject&#39;; 
$Mail->message = &#39;My message here&#39;; 
if($Mail->Send()) 
{ 
  echo &#39;邮件已发送!&#39;; 
} 
else 
{ 
  echo $Mail->error; 
} 
// 例3 (mail from another user: example user2@site2.com) 
$Mail->mail_to = &#39;Recipient Name <recipientmail@domain.com>&#39;; 
$Mail->subject = &#39;My subject&#39;; 
$Mail->message = &#39;My message here&#39;; 
$Mail->from_name = &#39;User2 Name&#39;; 
$Mail->SendFromMail = &#39;user2@site2.com&#39;; 
if($Mail->Send()) 
{ 
  echo &#39;message Mail send!&#39;; 
} 
else 
{ 
  echo $Mail->error; 
} 
?>

以上是php:smtp方式或mail函数方式发送邮件的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么将url的参数转化成数组php怎么将url的参数转化成数组Apr 21, 2022 pm 08:50 PM

转化方法:1、使用“mb_substr($url,stripos($url,"?")+1)”获取url的参数部分;2、使用“parse_str("参数部分",$arr)”将参数解析到变量中,并传入指定数组中,变量名转为键名,变量值转为键值。

php怎么禁止smtp邮件功能php怎么禁止smtp邮件功能Mar 22, 2023 pm 03:22 PM

PHP是一种强大的编程语言,广泛应用于Web开发领域中,其中SMTP邮件功能也是PHP开发中的重要一环。但是,在某些情况下,您可能希望禁止SMTP邮件功能,本文将介绍如何实现。

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尊渡假赌尊渡假赌尊渡假赌

热工具

SecLists

SecLists

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

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具