萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 基於 Socket 實作 SMTP 郵件發送

前言

不依賴 mail() 函式或第三方庫,直接使用 PHP Socket 擴充套件實作 SMTP 協定發送郵件,可深入理解郵件傳輸流程,亦適用於無法安裝擴充套件的受限環境。

完整類別實作

<?php
class SocketSmtpMailer
{
    private $host;
    private $port;
    private $username;
    private $password;
    private $from;
    private $to;
    private $subject;
    private $body;
    private $isHtml = false;
    private $socket;
    private $error = '';

    public function __construct($config = [])
    {
        foreach ($config as $k => $v) {
            if (property_exists($this, '_' . $k)) {
                $this->{'_' . $k} = $v;
            }
        }
    }

    public function setServer($host, $port = 25)
    {
        $this->host = $host;
        $this->port = $port;
    }

    public function setAuth($username, $password)
    {
        $this->username = $username;
        $this->password = $password;
    }

    public function setFrom($email) { $this->from = $email; }
    public function setTo($email) { $this->to = $email; }
    public function setSubject($subject) { $this->subject = $subject; }
    public function setBody($body, $isHtml = false) { $this->body = $body; $this->isHtml = $isHtml; }

    public function send()
    {
        $commands = $this->buildCommands();
        $this->connect();

        foreach ($commands as [$cmd, $expectedCode]) {
            if (!$this->sendCommand($cmd, $expectedCode)) {
                return false;
            }
        }
        $this->close();
        return true;
    }

    public function getError() { return $this->error; }

    private function connect()
    {
        $this->socket = @fsockopen($this->host, $this->port, $errno, $errstr, 30);
        if (!$this->socket) {
            $this->error = "連線失敗 ($errno): $errstr";
            return false;
        }
        stream_set_timeout($this->socket, 10);
        $this->readResponse(); // 220
        return true;
    }

    private function buildCommands()
    {
        $boundary = '----=_Part_' . md5($this->from . time()) . uniqid();
        $headers = "From: {$this->from}\r\n";
        $headers .= "To: {$this->to}\r\n";
        $headers .= "Subject: {$this->subject}\r\n";

        if ($this->isHtml) {
            $headers .= "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: text/html; charset=UTF-8\r\n\r\n";
            $body = $this->body;
        } else {
            $headers .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
            $body = $this->body;
        }

        $data = $headers . $body . "\r\n.\r\n";

        $cmds = [
            ['HELO ' . gethostname() . "\r\n", 250],
        ];

        if ($this->username) {
            $cmds[] = ['AUTH LOGIN\r\n', 334];
            $cmds[] = [base64_encode($this->username) . "\r\n", 334];
            $cmds[] = [base64_encode($this->password) . "\r\n", 235];
        }

        $cmds[] = ['MAIL FROM:<' . $this->from . ">\r\n", 250];
        $cmds[] = ['RCPT TO:<' . $this->to . ">\r\n", 250];
        $cmds[] = ['DATA\r\n', 354];
        $cmds[] = [$data, 250];
        $cmds[] = ['QUIT\r\n', 221];

        return $cmds;
    }

    private function sendCommand($cmd, $expectedCode)
    {
        fwrite($this->socket, $cmd);
        $response = $this->readResponse();
        if ($expectedCode && !preg_match('/^' . $expectedCode . ' /', $response)) {
            $this->error = "指令失敗: $cmd 回應: $response";
            return false;
        }
        return true;
    }

    private function readResponse()
    {
        $response = '';
        while ($line = fgets($this->socket, 512)) {
            $response .= $line;
            if (preg_match('/^\d{3} /', $line)) break;
        }
        return trim($response);
    }

    private function close()
    {
        if ($this->socket) {
            fclose($this->socket);
            $this->socket = null;
        }
    }
}
?>

使用範例

<?php
require 'SocketSmtpMailer.php';

$config = [
    'host' => 'smtp.163.com',
    'port' => 25,
    'username' => 'your@163.com',
    'password' => 'your_password',
    'from' => 'your@163.com',
    'to' => 'target@example.com',
    'subject' => 'Socket SMTP 測試',
    'body' => '<h1>HTML 郵件測試</h1><p>這是透過 Socket 發送的郵件</p>',
    'isHtml' => true,
];

$mailer = new SocketSmtpMailer($config);
if ($mailer->send()) {
    echo '發送成功';
} else {
    echo '發送失敗: ' . $mailer->getError();
}
?>

SSL/TLS 支援說明

上述實作為純文字/STARTTLS 前的明文連線。若需 SSL(port 465)或 STARTTLS(port 587),需改用 stream_socket_client 搭配 ssl:// 或 stream_socket_enable_crypto,參考前文《PHP 實作支援 SSL 的 SMTP 郵件發送類別》。

注意事項

  • 需開啟 PHP sockets 擴充套件(extension=sockets)。
  • 部分郵件伺服器要求 HELO 使用完整網域名稱(FQDN)。
  • 大量發送建議使用佇列系統,避免阻塞 PHP 行程。
  • 生產環境強烈建議使用成熟庫:PHPMailer、Symfony Mailer、Laravel Mail。

總結

Socket 實作 SMTP 是理解郵件協定的優秀練習,但生產環境請使用成熟庫處理編碼、MIME、附件、加密、重試、佇列等複雜細節。

copyright © 萬盛學電腦網 all rights reserved