検索
ホームページバックエンド開発PHPチュートリアルPHP: smtp またはメール関数経由で電子メールを送信する

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 またはメール関数経由で電子メールを送信するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
セッションを保存するためにデータベースを使用することの利点は何ですか?セッションを保存するためにデータベースを使用することの利点は何ですか?Apr 24, 2025 am 12:16 AM

データベースストレージセッションを使用することの主な利点には、持続性、スケーラビリティ、セキュリティが含まれます。 1。永続性:サーバーが再起動しても、セッションデータは変更されないままになります。 2。スケーラビリティ:分散システムに適用され、セッションデータが複数のサーバー間で同期されるようにします。 3。セキュリティ:データベースは、機密情報を保護するための暗号化されたストレージを提供します。

PHPでカスタムセッション処理をどのように実装しますか?PHPでカスタムセッション処理をどのように実装しますか?Apr 24, 2025 am 12:16 AM

PHPでのカスタムセッション処理の実装は、SessionHandlerInterfaceインターフェイスを実装することで実行できます。具体的な手順には、次のものが含まれます。1)CussentsessionHandlerなどのSessionHandlerInterfaceを実装するクラスの作成。 2)セッションデータのライフサイクルとストレージ方法を定義するためのインターフェイス(オープン、クローズ、読み取り、書き込み、破壊、GCなど)の書き換え方法。 3)PHPスクリプトでカスタムセッションプロセッサを登録し、セッションを開始します。これにより、データをMySQLやRedisなどのメディアに保存して、パフォーマンス、セキュリティ、スケーラビリティを改善できます。

セッションIDとは何ですか?セッションIDとは何ですか?Apr 24, 2025 am 12:13 AM

SessionIDは、ユーザーセッションのステータスを追跡するためにWebアプリケーションで使用されるメカニズムです。 1.ユーザーとサーバー間の複数のインタラクション中にユーザーのID情報を維持するために使用されるランダムに生成された文字列です。 2。サーバーは、ユーザーの複数のリクエストでこれらの要求を識別および関連付けるのに役立つCookieまたはURLパラメーターを介してクライアントに生成および送信します。 3.生成は通常、ランダムアルゴリズムを使用して、一意性と予測不可能性を確保します。 4.実際の開発では、Redisなどのメモリ内データベースを使用してセッションデータを保存してパフォーマンスとセキュリティを改善できます。

ステートレス環境(APIなど)でセッションをどのように処理しますか?ステートレス環境(APIなど)でセッションをどのように処理しますか?Apr 24, 2025 am 12:12 AM

APIなどのステートレス環境でのセッションの管理は、JWTまたはCookieを使用して達成できます。 1。JWTは、無国籍とスケーラビリティに適していますが、ビッグデータに関してはサイズが大きいです。 2.cookiesはより伝統的で実装が簡単ですが、セキュリティを確保するために慎重に構成する必要があります。

セッションに関連するクロスサイトスクリプティング(XSS)攻撃からどのように保護できますか?セッションに関連するクロスサイトスクリプティング(XSS)攻撃からどのように保護できますか?Apr 23, 2025 am 12:16 AM

セッション関連のXSS攻撃からアプリケーションを保護するには、次の測定が必要です。1。セッションCookieを保護するためにHTTPonlyとセキュアフラグを設定します。 2。すべてのユーザー入力のエクスポートコード。 3.コンテンツセキュリティポリシー(CSP)を実装して、スクリプトソースを制限します。これらのポリシーを通じて、セッション関連のXSS攻撃を効果的に保護し、ユーザーデータを確保できます。

PHPセッションのパフォーマンスを最適化するにはどうすればよいですか?PHPセッションのパフォーマンスを最適化するにはどうすればよいですか?Apr 23, 2025 am 12:13 AM

PHPセッションのパフォーマンスを最適化する方法は次のとおりです。1。遅延セッション開始、2。データベースを使用してセッションを保存します。これらの戦略は、高い並行性環境でのアプリケーションの効率を大幅に改善できます。

session.gc_maxlifetime構成設定とは何ですか?session.gc_maxlifetime構成設定とは何ですか?Apr 23, 2025 am 12:10 AM

thesession.gc_maxlifettinginttinginphpdethinesthelifsessessiondata、setinseconds.1)it'sconfiguredinphp.iniorviaini_set()。 2)AbalanceSneededToAvoidPerformanceIssues andunexpectedLogouts.3)php'sgarbagecollectionisisprobabilistic、影響を受けたBygc_probabi

PHPでセッション名をどのように構成しますか?PHPでセッション名をどのように構成しますか?Apr 23, 2025 am 12:08 AM

PHPでは、session_name()関数を使用してセッション名を構成できます。特定の手順は次のとおりです。1。session_name()関数を使用して、session_name( "my_session")などのセッション名を設定します。 2。セッション名を設定した後、session_start()を呼び出してセッションを開始します。セッション名の構成は、複数のアプリケーション間のセッションデータの競合を回避し、セキュリティを強化することができますが、セッション名の一意性、セキュリティ、長さ、設定タイミングに注意してください。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

WebStorm Mac版

WebStorm Mac版

便利なJavaScript開発ツール

mPDF

mPDF

mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。