萬盛學電腦網

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

PHP 實作支援 SSL 的 SMTP 郵件發送類別

前言

現代郵件伺服器(Gmail、Outlook、QQ 郵箱、企業郵箱)多要求 SSL/TLS 加密連線。本文提供完整的 PHP SMTP 類別,支援純文字/HTML 郵件、多收件人、抄送/密件副本、附件、SSL/TLS 連線,僅需 sockets、openssl、fileinfo 擴充套件。

完整類別程式碼

<?php
/**
 * SMTP 郵件發送類
 * 支援:SSL/TLS、HTML/純文字、多收件人/CC/BCC、附件、Base64 編碼、UTF-8
 */
class SmtpMailer
{
    // 伺服器設定
    private $host = '';
    private $port = 25;
    private $username = '';
    private $password = '';
    private $ssl = false;        // true=SSL (port 465), false=TLS/STARTTLS (port 587) 或無加密
    private $tls = false;        // STARTTLS 模式

    // 郵件內容
    private $from = '';
    private $fromName = '';
    private $to = [];
    private $cc = [];
    private $bcc = [];
    private $subject = '';
    private $bodyText = '';
    private $bodyHtml = '';
    private $attachments = [];   // ['path' => '/path/file.pdf', 'name' => 'file.pdf', 'mime' => 'application/pdf']

    // 內部
    private $socket = null;
    private $error = '';

    // ===== 設定方法 =====
    public function setServer($host, $port = 25, $ssl = false, $tls = false)
    {
        $this->host = $host;
        $this->port = (int)$port;
        $this->ssl = (bool)$ssl;
        $this->tls = (bool)$tls;
        return $this;
    }

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

    public function setFrom($email, $name = '')
    {
        $this->from = $email;
        $this->fromName = $name;
        return $this;
    }

    public function addTo($email, $name = '')
    {
        $this->to[] = ['email' => $email, 'name' => $name];
        return $this;
    }

    public function addCc($email, $name = '')
    {
        $this->cc[] = ['email' => $email, 'name' => $name];
        return $this;
    }

    public function addBcc($email, $name = '')
    {
        $this->bcc[] = ['email' => $email, 'name' => $name];
        return $this;
    }

    public function setSubject($subject)
    {
        $this->subject = $subject;
        return $this;
    }

    public function setBody($text, $html = '')
    {
        $this->bodyText = $text;
        $this->bodyHtml = $html;
        return $this;
    }

    public function addAttachment($path, $name = '', $mime = '')
    {
        if (!file_exists($path) || !is_readable($path)) {
            $this->error = "附件不存在或不可讀: $path";
            return false;
        }
        $this->attachments[] = [
            'path' => $path,
            'name' => $name ?: basename($path),
            'mime' => $mime ?: mime_content_type($path),
        ];
        return true;
    }

    // ===== 發送核心 =====
    public function send()
    {
        if (!$this->connect()) return false;
        if (!$this->handshake()) return false;
        if (!$this->sendMail()) return false;
        $this->close();
        return true;
    }

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

    private function connect()
    {
        $flags = STREAM_CLIENT_CONNECT;
        $remote = ($this->ssl ? 'ssl://' : 'tcp://') . $this->host . ':' . $this->port;

        $this->socket = @stream_socket_client($remote, $errno, $errstr, 30, $flags);
        if (!$this->socket) {
            $this->error = "連線失敗 ($errno): $errstr";
            return false;
        }

        stream_set_timeout($this->socket, 10);
        $this->readResponse(); // 220 歡迎訊息

        if ($this->tls && !$this->ssl) {
            $this->sendCommand('STARTTLS');
            $this->readResponse(220);
            // 升級為 TLS
            if (!stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                $this->error = 'STARTTLS 升級失敗';
                return false;
            }
            $this->readResponse(); // 再次讀取歡迎訊息
        }
        return true;
    }

    private function handshake()
    {
        $this->sendCommand('EHLO ' . gethostname());
        $this->readResponse(250);

        if ($this->username) {
            $this->sendCommand('AUTH LOGIN');
            $this->readResponse(334);
            $this->sendCommand(base64_encode($this->username));
            $this->readResponse(334);
            $this->sendCommand(base64_encode($this->password));
            $this->readResponse(235);
        }
        return true;
    }

    private function sendMail()
    {
        $allRcpt = array_merge($this->to, $this->cc, $this->bcc);
        if (empty($this->from) || empty($allRcpt)) {
            $this->error = '寄件人或收件人為空';
            return false;
        }

        $this->sendCommand('MAIL FROM:<' . $this->from . '>');
        $this->readResponse(250);

        foreach ($allRcpt as $rcpt) {
            $this->sendCommand('RCPT TO:<' . $rcpt['email'] . '>');
            $this->readResponse(250);
        }

        $this->sendCommand('DATA');
        $this->readResponse(354);

        $this->writeData($this->buildMessage());

        $this->sendCommand('.');
        $this->readResponse(250);

        return true;
    }

    private function buildMessage()
    {
        $boundary = '----=_Part_' . md5($this->from . microtime()) . uniqid();
        $headers = [];

        $headers[] = 'From: ' . $this->formatAddress($this->from, $this->fromName);
        $headers[] = 'To: ' . implode(', ', array_map([$this, 'formatAddress'], array_column($this->to, 'email'), array_column($this->to, 'name')));
        if ($this->cc) {
            $headers[] = 'Cc: ' . implode(', ', array_map([$this, 'formatAddress'], array_column($this->cc, 'email'), array_column($this->cc, 'name')));
        }
        $headers[] = 'Subject: =?UTF-8?B?' . base64_encode($this->subject) . '?=';
        $headers[] = 'MIME-Version: 1.0';
        $headers[] = 'Content-Type: multipart/mixed; boundary="' . $boundary . '"';
        $headers[] = '';

        $message = implode("\r\n", $headers);

        // 文字/HTML 替代部分
        $message .= "--$boundary\r\n";
        $message .= "Content-Type: multipart/alternative; boundary=\"alt_$boundary\"\r\n\r\n";

        $message .= "--alt_$boundary\r\n";
        $message .= "Content-Type: text/plain; charset=UTF-8\r\n";
        $message .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $message .= base64_encode($this->bodyText) . "\r\n";

        if ($this->bodyHtml) {
            $message .= "--alt_$boundary\r\n";
            $message .= "Content-Type: text/html; charset=UTF-8\r\n";
            $message .= "Content-Transfer-Encoding: base64\r\n\r\n";
            $message .= base64_encode($this->bodyHtml) . "\r\n";
        }
        $message .= "--alt_$boundary--\r\n";

        // 附件
        foreach ($this->attachments as $att) {
            $content = file_get_contents($att['path']);
            $message .= "--$boundary\r\n";
            $message .= "Content-Type: {$att['mime']}; name=\"{$att['name']}\"\r\n";
            $message .= "Content-Transfer-Encoding: base64\r\n";
            $message .= "Content-Disposition: attachment; filename=\"{$att['name']}\"\r\n\r\n";
            $message .= chunk_split(base64_encode($content)) . "\r\n";
        }

        $message .= "--$boundary--\r\n";
        return $message;
    }

    private function formatAddress($email, $name = '')
    {
        if ($name) {
            return '=?' . 'UTF-8' . '?B?' . base64_encode($name) . '?= <' . $email . '>';
        }
        return '<' . $email . '>';
    }

    private function sendCommand($cmd)
    {
        fwrite($this->socket, $cmd . "\r\n");
    }

    private function readResponse($expectedCode = null)
    {
        $response = '';
        while ($line = fgets($this->socket, 512)) {
            $response .= $line;
            if (preg_match('/^\d{3} /', $line)) break;
        }
        if ($expectedCode && !preg_match('/^' . $expectedCode . ' /', $response)) {
            $this->error = "SMTP 錯誤: $response";
            return false;
        }
        return $response;
    }

    private function writeData($data)
    {
        fwrite($this->socket, $data);
    }

    private function close()
    {
        if ($this->socket) {
            @fwrite($this->socket, "QUIT\r\n");
            @fclose($this->socket);
            $this->socket = null;
        }
    }
}
?>

使用範例

Gmail (SSL, port 465)

<?php
require 'SmtpMailer.php';

$mail = new SmtpMailer();
$mail->setServer('smtp.gmail.com', 465, true)  // SSL
     ->setAuth('your@gmail.com', 'app_password') // 需使用應用程式密碼
     ->setFrom('your@gmail.com', 'Your Name')
     ->addTo('recipient@example.com', 'Recipient')
     ->addCc('cc@example.com')
     ->setSubject('測試郵件 - Gmail SSL')
     ->setBody('這是純文字內容', '<h1>這是 <b>HTML</b> 內容</h1>')
     ->addAttachment('/path/to/document.pdf');

if ($mail->send()) {
    echo '發送成功';
} else {
    echo '發送失敗: ' . $mail->getError();
}
?>

QQ 企業郵箱 / 163 / 126 (STARTTLS, port 587)

$mail->setServer('smtp.exmail.qq.com', 587, false, true) // STARTTLS
     ->setAuth('user@domain.com', 'password')
     ->setFrom('user@domain.com')
     ->addTo('target@example.com')
     ->setSubject('測試')
     ->setBody('內容')
     ->send();

常見問題排查

錯誤原因解決
連線逾時防火牆封鎖、port 錯誤、SSL/TLS 模式不符telnet 測試 port、確認 SSL/STARTTLS 設定
認證失敗帳密錯誤、未開啟 SMTP 服務、需應用程式密碼確認郵箱設定、生成應用程式密碼
SSL 憑證驗證失敗自簽憑證、CA 不受信stream_context 設定 verify_peer=false (僅測試用)
附件亂碼檔名編碼問題使用 RFC 2231 編碼或 Base64 編碼檔名

總結

此類別封裝了完整 SMTP 協定流程,支援主流郵件服務商的加密需求,可直接整合至專案或作為學習 SMTP 協定的參考。

copyright © 萬盛學電腦網 all rights reserved