Skip to content

Nuface Blog

隨意隨手記 Casual Notes

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

Testing SMTP with PHP (PHP 7.4 Example)

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

When setting up a mail server (like Postfix + Dovecot) or debugging email delivery, it’s often necessary to verify whether your SMTP host works correctly and if your credentials are valid.
Here are two practical methods you can use with PHP 7.4.


✅ Method 1: Using PHPMailer (Recommended)

PHPMailer is a full-featured mailer library supporting STARTTLS / SMTPS / AUTH LOGIN and detailed debugging logs.

Install via Composer

composer require phpmailer/phpmailer:^6.8

Example: smtp_test.php

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

require __DIR__ . '/vendor/autoload.php';

$mail = new PHPMailer(true);

$host     = 'smtp.example.com';
$port     = 587;
$username = 'user@example.com';
$password = 'your_password';
$from     = 'user@example.com';
$to       = 'you@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 Test Email';
    $mail->Body    = 'This is a test message sent using PHPMailer.';

    $mail->send();
    echo "✅ Email sent successfully.\n";
} catch (Exception $e) {
    echo "❌ Mail send failed: {$mail->ErrorInfo}\n";
}

If you don’t use Composer, manually include PHPMailer.php, SMTP.php, and Exception.php from the official PHPMailer repository.


✅ Method 2: Pure PHP Socket Test (No Email Sent)

This method only checks connection → STARTTLS → AUTH LOGIN, without sending an actual message.
It’s perfect for quickly validating SMTP connectivity and authentication.

<?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("Expected {$desc} reply {$prefix}, got:\n{$line}");
    }
    echo "✔ {$desc}:\n{$line}\n";
    return $line;
}

$fp = stream_socket_client("tcp://{$host}:{$port}", $errno, $errstr, 10);
expect($fp, '220', 'Greeting');
fwrite($fp, "EHLO test.local\r\n");
expect($fp, '250', 'EHLO');

fwrite($fp, "STARTTLS\r\n");
expect($fp, '220', 'STARTTLS ready');
stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);

fwrite($fp, "EHLO test.local\r\n");
expect($fp, '250', 'EHLO after TLS');
fwrite($fp, "AUTH LOGIN\r\n");
expect($fp, '334', 'AUTH started');
fwrite($fp, base64_encode($user) . "\r\n");
expect($fp, '334', 'Username accepted');
fwrite($fp, base64_encode($pass) . "\r\n");
expect($fp, '235', 'Authentication successful');
fwrite($fp, "QUIT\r\n");
fclose($fp);
echo "✅ Connection + STARTTLS + AUTH successful.\n";

🔍 Common Issues

ErrorCause & Fix
Connection timed outWrong hostname or blocked port
Peer certificate CN mismatchCertificate’s CN/SAN doesn’t match host
535 Authentication failedWrong username/password or incomplete login format
STARTTLS not supportedYou’re using port 465 (SMTPS), which already uses TLS

🧩 Conclusion

If you need to send test emails, use PHPMailer.
If you want to debug TLS or AUTH handshake, use the pure PHP socket script.
Both methods let you quickly verify if your SMTP server and credentials are working correctly.

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