在開發郵件系統或部署郵件伺服器(如 Postfix、Dovecot)時,常常需要快速驗證 SMTP 主機是否可用、帳號密碼是否正確。本文提供兩種實用方式,使用 PHP 7.4 即可輕鬆測試郵件寄送與認證。
✅ 方法一:使用 PHPMailer(推薦)
這是最直覺、最穩定的做法。
PHPMailer 支援 STARTTLS / SMTPS / AUTH LOGIN,並能顯示詳細的 SMTP 除錯訊息。
安裝
若可使用 Composer:
composer require phpmailer/phpmailer:^6.8
範例程式:smtp_test.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
require __DIR__ . '/vendor/autoload.php'; // 若無 Composer,見下方說明
$mail = new PHPMailer(true);
$host = 'smtp.example.com';
$port = 587;
$username = 'user@example.com';
$password = 'your_password';
$from = 'user@example.com';
$to = 'test@example.com';
try {
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = $host;
$mail->SMTPAuth = true;
$mail->Username = $username;
$mail->Password = $password;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = $port;
$mail->setFrom($from, 'SMTP Tester');
$mail->addAddress($to);
$mail->Subject = 'SMTP 測試信';
$mail->Body = '這是一封由 PHPMailer 發出的 SMTP 測試信。';
$mail->send();
echo "✅ 郵件已成功送出!";
} catch (Exception $e) {
echo "❌ 寄信失敗:" . $mail->ErrorInfo;
}
若無法使用 Composer,可直接下載 PHPMailer 的三個核心檔案:
PHPMailer.php,SMTP.php,Exception.php,並在程式中手動引用。
✅ 方法二:純 PHP Socket 測試(不發信,只測握手)
這個版本不寄信,只測試 連線 → STARTTLS → AUTH LOGIN 是否正常。
非常適合快速檢查主機、TLS 或帳密問題。
<?php
$host = 'smtp.example.com';
$port = 587;
$user = 'user@example.com';
$pass = 'your_password';
function expect($fp, $prefix, $desc) {
$line = '';
while ($row = fgets($fp)) {
$line .= $row;
if (strlen($row) >= 4 && $row[3] === ' ') break;
}
if (strpos($line, $prefix) !== 0) {
throw new RuntimeException("期望 {$desc} 回覆 {$prefix},實際:\n{$line}");
}
echo "✔ {$desc}:\n{$line}\n";
return $line;
}
$fp = stream_socket_client("tcp://{$host}:{$port}", $errno, $errstr, 10);
expect($fp, '220', '伺服器問候');
fwrite($fp, "EHLO test.local\r\n");
expect($fp, '250', 'EHLO');
fwrite($fp, "STARTTLS\r\n");
expect($fp, '220', 'STARTTLS');
stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
fwrite($fp, "EHLO test.local\r\n");
expect($fp, '250', 'TLS 後 EHLO');
fwrite($fp, "AUTH LOGIN\r\n");
expect($fp, '334', 'AUTH 啟動');
fwrite($fp, base64_encode($user) . "\r\n");
expect($fp, '334', '帳號接受');
fwrite($fp, base64_encode($pass) . "\r\n");
expect($fp, '235', '登入成功');
fwrite($fp, "QUIT\r\n");
fclose($fp);
echo "✅ 連線 + STARTTLS + 認證皆成功\n";
🔍 常見錯誤與排查
| 問題 | 原因與建議 |
|---|---|
Connection timed out | 主機或連接埠錯誤、防火牆阻擋 |
Peer certificate CN mismatch | 憑證主體名稱與主機名不符 |
535 Authentication failed | 帳密錯誤或伺服器要求完整 email 格式帳號 |
STARTTLS not supported | 使用錯誤埠號(465 為 SMTPS,不支援 STARTTLS) |
🧩 結語
若只是測試 SMTP 功能,PHPMailer 是最佳選擇;
若想更深入了解 TLS / AUTH 過程,可用純 PHP 版本分析。
這兩種方式都能協助你快速確認郵件伺服器設定是否正確。