Skip to content

Nuface Blog

隨意隨手記 Casual Notes

Menu
  • Home
  • About
  • Services
  • Blog
  • Contact
  • Privacy Policy
  • Login
Menu

使用 PHP 測試 SMTP 功能(PHP 7.4 範例)

Posted on 2025-11-062025-11-06 by Rico

在開發郵件系統或部署郵件伺服器(如 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 版本分析。
這兩種方式都能協助你快速確認郵件伺服器設定是否正確。

Recent Posts

  • Postfix + Let’s Encrypt + BIND9 + DANE Fully Automated TLSA Update Guide
  • Postfix + Let’s Encrypt + BIND9 + DANE TLSA 指紋自動更新完整教學
  • Deploying DANE in Postfix
  • 如何在 Postfix 中部署 DANE
  • DANE: DNSSEC-Based TLS Protection

Recent Comments

  1. Building a Complete Enterprise-Grade Mail System (Overview) - Nuface Blog on High Availability Architecture, Failover, GeoDNS, Monitoring, and Email Abuse Automation (SOAR)
  2. Building a Complete Enterprise-Grade Mail System (Overview) - Nuface Blog on MariaDB + PostfixAdmin: The Core of Virtual Domain & Mailbox Management
  3. Building a Complete Enterprise-Grade Mail System (Overview) - Nuface Blog on Daily Operations, Monitoring, and Performance Tuning for an Enterprise Mail System
  4. Building a Complete Enterprise-Grade Mail System (Overview) - Nuface Blog on Final Chapter: Complete Troubleshooting Guide & Frequently Asked Questions (FAQ)
  5. Building a Complete Enterprise-Grade Mail System (Overview) - Nuface Blog on Network Architecture, DNS Configuration, TLS Design, and Postfix/Dovecot SNI Explained

Archives

  • December 2025
  • November 2025
  • October 2025

Categories

  • AI
  • Apache
  • Cybersecurity
  • Database
  • DNS
  • Docker
  • Fail2Ban
  • FileSystem
  • Firewall
  • Linux
  • LLM
  • Mail
  • N8N
  • OpenLdap
  • OPNsense
  • PHP
  • QoS
  • Samba
  • Switch
  • Virtualization
  • VPN
  • WordPress
© 2025 Nuface Blog | Powered by Superbs Personal Blog theme