Home Backend Development PHP Tutorial PHP mail sending class (smtp method or mail function method)

PHP mail sending class (smtp method or mail function method)

Jul 25, 2016 am 08:56 AM

本文介绍下,一个用于email邮件发送的类,可以使用smtp与mail函数二种方式发送邮件,有需要的朋友参考下。

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

代码:

<?php 
/**
* 邮件发送类
* by bbs.it-home.org
*/
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 = ''; 
    public $ContentType = 'html'; 
    public $charset = 'windows-1251'; 
    public $smtp_debug = true; 
    public $socket; 
    public $error; 
    public $SendMailVia  = 'smtp'; 
     
  public function __construct() 
    { 
            if($this->SendFromMail == ''){ 
               $this->SendFromMail = $this->smtp_user; 
            } 
    } 
     
    public function Send($mail_to = '', $subject = '', $message = '') 
    { 
        if($mail_to!=''){$this->mail_to = stripslashes($mail_to);} 
            if($subject!=''){$this->subject = stripslashes($subject);} 
            if($message!=''){$this->message = $message;} 
            $meilsArr = array_filter($this->GetMailAndNameArr()); 
            if(trim($this->mail_to)==''){$this->error = 'Enter the recipient address'; } 
            if($meilsArr == array()){$this->error = 'Please enter a valid recipient address'; } 
            foreach ($meilsArr as $val) 
            { 
                $validEmail = $this->validEmail($val[2]); 
                if($validEmail) 
                { 
                  if($this->SendMailVia=='smtp'){ 
                      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 .=   'Subject: =?'.$this->charset.'?B?'.base64_encode($this->subject)."=?=\r\n"; 
            if ($this->headers!=''){ $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 = '<p>Can not send HELO!</p>'; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, "AUTH LOGIN\r\n"); 
            if (!$this->server_parse($socket, "334", __LINE__)) { 
               if ($this->smtp_debug) $this->error = '<p>Can not find an answer to a request authorization.</p>'; 
               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 = '<p>Login authorization was not accepted by server!</p>'; 
               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 = '<p>No password was not accepted as a true server! Authorization Error!</p>'; 
               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 = '<p>Unable to send command MAIL FROM: </p>'; 
               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 = '<p>Unable to send command RCPT TO: </p>'; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, "DATA\r\n"); 
            if (!$this->server_parse($socket, "354", __LINE__)) { 
               if ($this->smtp_debug) $this->error = '<p>Unable to send command DATA</p>'; 
               fclose($socket); 
               return false; 
            } 
            fputs($socket, $SEND."\r\n.\r\n"); 
            if (!$this->server_parse($socket, "250", __LINE__)) { 
               if ($this->smtp_debug) $this->error = '<p>Unable to send the message body. The letter was sent!</p>'; 
               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 = '/(.*?)<(.*?)>/i'; 
            foreach($tos as $to) 
            { 
              if(preg_match('/(.*?)<(.*?)>/i',$to,$matches)) 
                { 
                  unset($matches[0]);     
                  $matches[1] = trim(str_replace('"','',$matches[1])); 
                  $matches[2] = trim($matches[2]); 
                  $mailingArr[] =$matches;  
                } 
                elseif(preg_match('/\b([A-Z0-9._%-]+)@([A-Z0-9.-]+\.[A-Z]{2,4})\b/i',$to,$matches2)) 
                { 
                     unset($matches[0]);     
                     $matches[1] = trim(str_replace('"','',$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) != ' ') { 
          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 = ''; 
    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 = 'local part length exceeded'; 
         $isValid = false; 
      } 
      else if ($domainLen < 1 || $domainLen > 255){ 
                 $msg = ' domain part length exceeded '; 
         $isValid = false; 
      } 
      else if ($local[0] == '.' || $local[$localLen-1] == '.'){ 
                 $msg = ' local part starts or ends with .'; 
         $isValid = false; 
      } 
      else if (preg_match('/\\.\\./', $local)){ 
                 $msg = 'local part has two consecutive dots'; 
         $isValid = false; 
      } 
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)){ 
                 $msg = 'character not valid in domain part'; 
         $isValid = false; 
      } 
      else if (preg_match('/\\.\\./', $domain)){ 
                 $msg = '  domain part has two consecutive dots'; 
         $isValid = false; 
      } 
      else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))){ 
                 $msg = '  character not valid in local part unless local part is quoted'; 
         if (!preg_match('/^"(\\\\"|[^"])+"$/',str_replace("\\\\","",$local))){ 
            $isValid = false; 
         } 
      } 
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))){ 
                 $msg = '  domain <b>'.$domain.'</b> not found in DNS'; 
         $isValid = false; 
      } 
    } 
      $this->error = $msg; 
    return $isValid; 
  } 

} 
?>
Copy after login

调用示例:

<?php  
include "sendmail.class.php"; 
$Mail = new sendmail(); 

// Set congif 
$Mail->SendMailVia = 'smtp';  // Send via smtp server or mail function 
$Mail->smtp_host = 'mail.myhost.com'; 
$Mail->smtp_port = 25; 
$Mail->smtp_user = 'user@myhost.com'; 
$Mail->smtp_password = 'mypassw'; 

// 例1 (mail from me) 
if($Mail->Send('mymail1@mydomain.com; recipient2 name <recipientmail2@mydomain.com>,"recipient name" <recipient@mail.com>',
'My subject','My message here.')) 
{ 
  echo '邮件已发送!'; 
} 
else 
{ 
  echo $Mail->error; 
} 

// 例2 (mail from me) 
$Mail->mail_to = 'mymail1@mydomain.com; recipient2 name <recipientmail2@mydomain.com>,"recipient name" <recipient@mail.com>'; 
$Mail->subject = 'My subject'; 
$Mail->message = 'My message here'; 

if($Mail->Send()) 
{ 
  echo '邮件已发送!'; 
} 
else 
{ 
  echo $Mail->error; 
} 


// 例3 (mail from another user: example user2@site2.com) 

$Mail->mail_to = 'Recipient Name <recipientmail@domain.com>'; 
$Mail->subject = 'My subject'; 
$Mail->message = 'My message here'; 
$Mail->from_name = 'User2 Name'; 
$Mail->SendFromMail = 'user2@site2.com'; 

if($Mail->Send()) 
{ 
  echo 'message Mail send!'; 
} 
else 
{ 
  echo $Mail->error; 
} 

?>
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles