萬盛學電腦網

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

PHP 發送郵件完整指南:從 mail() 到 PHPMailer、SMTP 實戰

PHP 郵件發送演進史

PHP 發送郵件歷經三個時代:早期依賴系統 sendmail 的 mail() 函數;中期興起 SMTP 協議直連與 PHPMailer 等庫;現代則推薦使用 API 服務。本文系統梳理各方案優劣,助你選型。

方案一:原生 mail() 函數(不推薦生產環境)

<?php
$to = 'user@example.com';
$subject = '測試郵件';
$message = '這是使用 mail() 發送的郵件';
$headers = 'From: noreply@example.com' . "\r\n" .
           'Reply-To: support@example.com' . "\r\n" .
           'Content-Type: text/html; charset=UTF-8' . "\r\n" .
           'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>

缺點:依賴伺服器 sendmail/postfix 配置、無 SMTP 驗證、易進垃圾箱、不支援 SSL/TLS、無附件/HTML 完善支援、難以除錯。

方案二:CodeIgniter 內建 Email 類(框架整合範例)

<?php
$this->load->library('email');

$config = [
    'protocol'  => 'smtp',
    'smtp_host' => 'smtp.163.com',
    'smtp_port' => 465,           // SSL 埠
    'smtp_user' => 'your@163.com',
    'smtp_pass' => 'auth_code',   // 授權碼而非登入密碼
    'smtp_crypto' => 'ssl',       // 或 'tls' (port 587)
    'mailtype'  => 'html',
    'charset'   => 'utf-8',
    'wordwrap'  => true,
    'priority'  => 3,
    'crlf'      => "\r\n",
    'newline'   => "\r\n",
];

$this->email->initialize($config);
$this->email->from('your@163.com', '系統通知');
$this->email->to('target@example.com');
$this->email->subject('測試標題');
$this->email->message('<h1>HTML 內容</h1><p>支援中文</p>');
$this->email->attach('/path/to/file.pdf');

if ($this->email->send()) {
    echo '發送成功';
} else {
    show_error($this->email->print_debugger());
}
?>

方案三:PHPMailer(業界標準,強烈推薦)

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    // 伺服器設定
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'your@gmail.com';
    $mail->Password   = 'app_password';  // Gmail 需應用程式密碼
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // SSL
    $mail->Port       = 465;
    $mail->CharSet    = 'UTF-8';
    $mail->Timeout    = 30;

    // 發件人/收件人
    $mail->setFrom('your@gmail.com', '系統名稱');
    $mail->addAddress('user@example.com', '收件人姓名');
    $mail->addReplyTo('support@example.com', '客服');
    $mail->addCC('cc@example.com');
    $mail->addBCC('bcc@example.com');

    // 附件
    $mail->addAttachment('/path/to/file.pdf', 'rename.pdf');
    $mail->addStringAttachment($pdfContent, 'dynamic.pdf');

    // 內容
    $mail->isHTML(true);
    $mail->Subject = 'PHPMailer 測試';
    $mail->Body    = '<h1>你好</h1><p>這是 <b>HTML</b> 郵件</p>';
    $mail->AltBody = '純文字備用內容';

    $mail->send();
    echo '郵件已發送';
} catch (Exception $e) {
    echo "發送失敗: {$mail->ErrorInfo}";
}
?>

主流 SMTP 服務商配置對照表

服務商SMTP 主機SSL 埠TLS 埠備註
Gmailsmtp.gmail.com465587需開啟「低安全性應用」或使用應用程式密碼
Outlook/Hotmailsmtp-mail.outlook.com465587支援 OAuth2
163/126smtp.163.com465/99425/587需在網頁端開啟 SMTP 服務獲取授權碼
QQ 郵箱smtp.qq.com465587需生成授權碼
SendGridsmtp.sendgrid.net465587API Key 作為密碼,用戶名固定為 apikey
Mailgunsmtp.mailgun.org465587需驗證域名
Amazon SESemail-smtp.region.amazonaws.com465587需申請移出沙箱

替代方案:交易式郵件 API(現代首選)

對於高並發、高送達率需求,建議直接呼叫 HTTP API:

  • SendGrid:POST /v3/mail/send,免費額度 100/天
  • Mailgun:POST /v3/yourdomain/messages,免費額度 5,000/月
  • Postmark:專注交易郵件,送達率極高
  • Amazon SES:成本最低 ($0.10/千封),需自行處理退信/投訴
  • 國內服務:騰訊雲郵件推送、阿里雲郵件推送、Submail、SendCloud
<?php
// SendGrid API 範例
function sendViaSendGrid(string $apiKey, array $params): bool
{
    $url = 'https://api.sendgrid.com/v3/mail/send';
    $data = [
        'personalizations' => [[
            'to' => [['email' => $params['to']]],
            'subject' => $params['subject'],
        ]],
        'from' => ['email' => $params['from_email'], 'name' => $params['from_name']],
        'content' => [[
            'type' => 'text/html',
            'value' => $params['html'],
        ]],
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json',
        ],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
    ]);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $httpCode === 202;
}
?>

常見坑位與解決方案

問題原因解決
連線逾時防火牆封鎖 25/465/587 埠使用 587 TLS 或 465 SSL;檢查安全群組/防火牆
認證失敗密碼錯誤/未開啟 SMTP使用授權碼/應用程式密碼;在郵箱設定開啟 SMTP
進垃圾箱缺 SPF/DKIM/DMARC、IP 信譽差配置域名 DNS 記錄;使用專業郵件服務商
中文亂碼編碼不一致統一 UTF-8;設定 CharSet、headers 正確
大量發送被封觸發頻率限制使用佇列限流;分批發送;遷移至 API 服務

架構建議:佇列化發送

<?php
// Laravel 隊列 Job 範例
class SendEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;
    public $backoff = [60, 300, 900]; // 1分、5分、15分重試

    public function __construct(
        public string $to,
        public string $subject,
        public string $html,
        public array $attachments = []
    ) {}

    public function handle(Mailer $mailer)
    {
        $mailer->send(new GenericMail($this->to, $this->subject, $this->html, $this->attachments));
    }
}

// 控制器中分發
SendEmailJob::dispatch($user->email, '歡迎註冊', $htmlContent)
    ->onQueue('emails');
?>

總結與選型建議

  • 簡單專案/學習:PHPMailer + Gmail/163 SMTP
  • 中型應用:PHPMailer + 專業 SMTP (SendGrid/Mailgun) + 佇列
  • 大規模/高送達率:直接對接交易郵件 API + 監控/退信處理
  • 國內合規:阿里雲/騰訊雲郵件推送 + 已備案域名

核心原則:絕不在 HTTP 請求中同步發送郵件,務必異步佇列化,並建立完善的發送日誌、退信追蹤、送達率監控體系。

copyright © 萬盛學電腦網 all rights reserved