萬盛學電腦網

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

PHPMailer 完整使用指南:SMTP 配置、異步發送、附件處理、錯誤排查

一、環境準備

1. 安裝 PHPMailer

# Composer (推薦)
composer require phpmailer/phpmailer

# 或手動下載:https://github.com/PHPMailer/PHPMailer

2. 服務器郵件服務配置

方案 A:本地 Sendmail/Postfix(簡單但送達率低)

# Ubuntu/Debian
sudo apt-get install postfix
sudo systemctl enable postfix
sudo systemctl start postfix

# php.ini
sendmail_path = /usr/sbin/sendmail -t -i

方案 B:SMTP 服務商(推薦:SendGrid、Mailgun、阿里雲郵件、騰訊雲郵件)

  • 高送達率、退信追蹤、API 統計、DKIM/SPF 自動配置
  • PHPMailer 使用 SMTP 模式連接

二、核心發送函數封裝

<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

/**
 * 發送郵件統一入口
 * @param string|array $to 收件人,單個或數組
 * @param string $subject 主題
 * @param string $body HTML 內容
 * @param array $attachments 附件 ['path'=>'', 'name'=>'', 'type'=>'']
 * @param array $options 額外選項
 * @return bool|array 成功返回 true,失敗返回 ['error'=>...]
 */
function sendMail($to, $subject, $body, array $attachments = [], array $options = []) {
    $mail = new PHPMailer(true); // true = 拋出異常
    
    try {
        // === 基礎配置 ===
        $mail->CharSet = 'UTF-8';
        $mail->Encoding = 'base64';
        
        // === 發送模式選擇 ===
        $useSmtp = $options['smtp'] ?? true;
        if ($useSmtp) {
            // SMTP 模式(生產推薦)
            $mail->isSMTP();
            $mail->Host       = $options['smtp_host'] ?? 'smtp.example.com';
            $mail->Port       = $options['smtp_port'] ?? 587; // 587 TLS, 465 SSL
            $mail->SMTPSecure = $options['smtp_secure'] ?? PHPMailer::ENCRYPTION_STARTTLS; // TLS
            $mail->SMTPAuth   = true;
            $mail->Username   = $options['smtp_user'] ?? 'user@example.com';
            $mail->Password   = $options['smtp_pass'] ?? 'password';
            // $mail->SMTPDebug = SMTP::DEBUG_SERVER; // 調試輸出
        } else {
            // mail() 函數模式(簡單但不可靠)
            $mail->isMail();
        }
        
        // === 發件人 ===
        $mail->setFrom(
            $options['from_email'] ?? 'noreply@example.com',
            $options['from_name'] ?? '系統通知'
        );
        $mail->addReplyTo($options['reply_to'] ?? $options['from_email'] ?? 'noreply@example.com');
        
        // === 收件人 ===
        $recipients = is_array($to) ? $to : [$to];
        foreach ($recipients as $rcpt) {
            if (is_array($rcpt)) {
                $mail->addAddress($rcpt[0], $rcpt[1] ?? '');
            } else {
                $mail->addAddress($rcpt);
            }
        }
        
        // === 抄送/密送 ===
        if (!empty($options['cc'])) {
            foreach ((array)$options['cc'] as $cc) $mail->addCC($cc[0] ?? $cc, $cc[1] ?? '');
        }
        if (!empty($options['bcc'])) {
            foreach ((array)$options['bcc'] as $bcc) $mail->addBCC($bcc[0] ?? $bcc, $bcc[1] ?? '');
        }
        
        // === 內容 ===
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->AltBody = $options['alt_body'] ?? strip_tags($body); // 純文本備選
        
        // === 附件 ===
        foreach ($attachments as $att) {
            $path = $att['path'] ?? $att;
            $name = $att['name'] ?? basename($path);
            $encoding = $att['encoding'] ?? 'base64';
            $type = $att['type'] ?? 'application/octet-stream';
            if (file_exists($path)) {
                $mail->addAttachment($path, $name, $encoding, $type);
            } else {
                error_log("郵件附件不存在: $path");
            }
        }
        
        // === 發送 ===
        $mail->send();
        return true;
        
    } catch (Exception $e) {
        error_log("PHPMailer 錯誤: {$mail->ErrorInfo}");
        return ['error' => $mail->ErrorInfo, 'code' => $mail->getErrorCode()];
    }
}
?>

三、使用示例

1. 簡單 HTML 郵件

<?php
$result = sendMail(
    'user@example.com',
    '歡迎註冊',
    '<h1>歡迎</h1><p>感謝註冊,您的驗證碼:<strong>123456</strong></p>'
);
if ($result === true) echo "發送成功";
else echo "失敗: " . $result['error'];
?>

2. 帶附件郵件

<?php
$attachments = [
    ['path' => '/data/reports/monthly.pdf', 'name' => '月報.pdf'],
    ['path' => '/data/images/chart.png', 'name' => '圖表.png', 'type' => 'image/png'],
];
sendMail('boss@company.com', '月度報告', '請查收附件', $attachments);

3. 批量發送(高效復用 SMTP 連接)

<?php
function sendBatch(array $recipients, $subject, $body, array $attachments = []) {
    $mail = new PHPMailer(true);
    // ... 配置 SMTP、發件人等(同上,不重複) ...
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body = $body;
    
    foreach ($attachments as $att) {
        $mail->addAttachment($att['path'], $att['name'] ?? '');
    }
    
    $results = [];
    foreach ($recipients as $to) {
        // 清除上一輪收件人
        $mail->clearAddresses();
        $mail->addAddress($to['email'], $to['name'] ?? '');
        
        try {
            $mail->send();
            $results[$to['email']] = true;
        } catch (Exception $e) {
            $results[$to['email']] = $mail->ErrorInfo;
            // 記錄失敗,繼續發送下一個
        }
    }
    return $results;
}
?>

四、常見問題排查表

錯誤現象可能原因解決方案
SMTP connect() failed端口阻塞、主機錯誤、防火牆telnet 檢查端口、檢查安全組、嘗試 465/587/2525
Authentication failed用戶名/密碼錯誤、需授權碼確認 SMTP 密碼/授權碼、開啟「客戶端授權」
Certificate verification failed自簽證書、CA 不信任$mail->SMTPOptions = ['ssl'=>['verify_peer'=>false,'verify_peer_name'=>false]] (僅測試)
郵件進垃圾箱無 SPF/DKIM/DMARC、內容觸發規則配置域名記錄、優化內容、使用專業服務商
中文亂碼CharSet 未設置、編碼不匹配$mail->CharSet = 'UTF-8'; $mail->Encoding = 'base64';
大附件發送失敗post_max_size/upload_max_filesize/memory_limit調整 php.ini、分片上傳、雲存儲鏈接代替附件

五、生產環境最佳實踐

  1. 異步發送:HTTP 請求中將郵件任務推入隊列,Worker 消費發送
    
    // 生產者
    Redis::lpush('mail_queue', json_encode(['to'=>..., 'subject'=>..., 'body'=>...]));
    
    // 消費者
    while (true) {
        $task = Redis::rpop('mail_queue');
        if ($task) sendMail(...json_decode($task, true)...);
        usleep(100000);
    }
    
  2. 模版引擎:使用 Blade/Twig/自定義模版分離內容與邏輯
  3. 發送限流:單 IP/用戶/域名頻率限制,防濫發
  4. 退信處理:配置 Webhook 接收 Bounce/Complaint,自動清理列表
  5. 監控告警:發送成功率、隊列堆積、SMTP 錯誤率實時監控

六、安全加固

  • ✅ SMTP 密碼存儲在環境變量/密鑰管理系統,絕不提交代碼倉庫
  • ✅ 禁用 allow_url_include、disable_functions 包含 mail 相關危險函數
  • ✅ 郵件內容用戶輸入部分必須 HTMLPurifier 過濾
  • ✅ 附件類型白名單、大小限制、病毒掃描

PHPMailer 是 PHP 郵件發送的事實標準,配合 SMTP 服務商、異步隊列、模版引擎,能構建企業級可靠郵件系統。

copyright © 萬盛學電腦網 all rights reserved