Send SMTP Mail with PHPMailer in PHP

To submit mail from PHP over the Simple Mail Transfer Protocol (SMTP), install PHPMailer and configure your server, port, TLS mode, and credentials. Start with a local mail catcher to verify the subject and body before using your provider.

Install PHPMailer and prepare the files

Install PHP 8.3 and Composer. Enable PHP’s OpenSSL extension for connections over TLS. Run Composer’s require command in the project directory to create vendor/autoload.php.

composer require phpmailer/phpmailer
mail-demo/
  vendor/autoload.php
  smtp-mailer.php
  send.php
  public/form.php

Save the files below in that project. The examples were verified with PHP 8.3.32 and PHPMailer 7.4.1. If Composer is unavailable on the host, deploy dependencies built elsewhere or follow the manual loader instructions in the PHPMailer repository. Use public as the web document root for the local form.

Capture a UTF-8 message locally

Run Mailpit installation guide with SMTP on 127.0.0.1:1025 and the message list on 127.0.0.1:8025. Leave forwarding and relaying off. Save both PHP files and run php send.php.

mailpit --smtp 127.0.0.1:1025 --listen 127.0.0.1:8025
<?php
declare(strict_types=1);

use PHPMailer\PHPMailer\PHPMailer;

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

function requiredSmtpEnv(string $name): string
{
    $value = getenv($name);
    if ($value === false || $value === '') {
        throw new RuntimeException("Missing SMTP setting: $name");
    }
    return $value;
}

function smtpPort(string $value): int
{
    $port = filter_var($value, FILTER_VALIDATE_INT, [
        'options' => ['min_range' => 1, 'max_range' => 65535],
    ]);
    if ($port === false) {
        throw new InvalidArgumentException('Invalid SMTP port.');
    }
    return $port;
}

function validMailInput(mixed $subject, mixed $body): bool
{
    return is_string($subject) && is_string($body)
        && trim($subject) !== '' && strlen($subject) <= 300
        && strpbrk($subject, "\r\n") === false
        && trim($body) !== '' && strlen($body) <= 10000;
}

function sendDemoMail(string $subject, string $body, bool $capture): void
{
    if (!validMailInput($subject, $body)) {
        throw new InvalidArgumentException('Invalid subject or body.');
    }

    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->Timeout = 10;
    $mail->CharSet = PHPMailer::CHARSET_UTF8;
    $mail->SMTPDebug = 0;

    if ($capture) {
        $mail->Host = '127.0.0.1';
        $mail->Port = smtpPort(getenv('SMTP_CAPTURE_PORT') ?: '1025');
        $mail->SMTPAutoTLS = false;
        $mail->setFrom('app@example.test');
        $mail->addAddress('tester@example.test');
    } else {
        if (!extension_loaded('openssl')) {
            throw new RuntimeException('Load the OpenSSL extension for SMTP over TLS.');
        }
        $host = requiredSmtpEnv('SMTP_HOST');
        if (!filter_var($host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)) {
            throw new InvalidArgumentException('Use a single SMTP hostname or IPv4 address.');
        }
        $mail->Host = $host;
        $mail->Port = smtpPort(requiredSmtpEnv('SMTP_PORT'));
        $mail->SMTPSecure = match (requiredSmtpEnv('SMTP_SECURITY')) {
            'starttls' => PHPMailer::ENCRYPTION_STARTTLS,
            'smtps' => PHPMailer::ENCRYPTION_SMTPS,
            default => throw new InvalidArgumentException('Choose starttls or smtps.'),
        };
        $mail->SMTPAuth = true;
        $mail->Username = requiredSmtpEnv('SMTP_USER');
        $mail->Password = requiredSmtpEnv('SMTP_PASS');
        $mail->setFrom(requiredSmtpEnv('SMTP_FROM'));
        $mail->addAddress(requiredSmtpEnv('SMTP_TO'));
    }

    $mail->isHTML(false);
    $mail->Subject = $subject;
    $mail->Body = $body;
    $mail->send();
}
<?php
declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(404);
    exit;
}
require __DIR__ . '/smtp-mailer.php';

$mode = $argv[1] ?? 'capture';
if (!in_array($mode, ['capture', 'send'], true)) {
    fwrite(STDERR, "Usage: php send.php [capture|send]\n");
    exit(2);
}
try {
    sendDemoMail('SMTP test – café', "UTF-8: café / 한글\nSecond line.", $mode === 'capture');
    echo "Accepted by the SMTP server.\n";
} catch (Throwable $error) {
    fwrite(STDERR, "SMTP submission failed. Check settings and private logs.\n");
    exit(1);
}
php send.php

The default mode is capture. When the local server accepts the message, the script prints Accepted by the SMTP server. In Mailpit, check the subject SMTP test – café and the body with café / 한글 and a line break. The CharSet property sets UTF-8 for the message. This loopback-only mode is the only unencrypted branch.

Configure TLS and credentials for real submission

Check your provider’s Host, Port, and SMTPSecure combination. In RFC 8314, STARTTLS upgrades an existing connection and commonly uses port 587. SMTPS starts in TLS and commonly uses port 465. Replace the example settings with those for an authorized account.

export SMTP_HOST='smtp.example.com'
export SMTP_PORT='587'
export SMTP_SECURITY='starttls'
export SMTP_USER='sender@example.com'
export SMTP_FROM='sender@example.com'
export SMTP_TO='recipient@example.com'
read -r -s -p 'SMTP password: ' SMTP_PASS
echo
export SMTP_PASS
php send.php send
unset SMTP_PASS

Use php send.php send to select your configured SMTP server. Supply the password through your environment’s secret configuration. Check that it reaches the PHP process when using FPM or Apache. Use a provider-approved From address or alias and set a recipient on the server. If a form collects a visitor’s email, validate it before using it as Reply-To. For HTML mail, provide a plain-text AltBody.

Try a local form with a fixed recipient

Save the form as public/form.php, start PHP’s development server, and visit http://127.0.0.1:8080/form.php. The form only submits to the local mail catcher. A session token protects against cross-site request forgery (CSRF).

<?php
declare(strict_types=1);

if (PHP_SAPI !== 'cli-server' || ($_SERVER['REMOTE_ADDR'] ?? '') !== '127.0.0.1') {
    http_response_code(403);
    exit;
}
require dirname(__DIR__) . '/smtp-mailer.php';

session_start([
    'use_strict_mode' => 1,
    'cookie_httponly' => true,
    'cookie_samesite' => 'Strict',
]);
header('Content-Type: text/html; charset=UTF-8');
header('Cache-Control: no-store');

$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
$status = $_SESSION['notice'] ?? '';
unset($_SESSION['notice']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf'] ?? null;
    $subject = $_POST['subject'] ?? null;
    $body = $_POST['body'] ?? null;
    if (!is_string($token) || !hash_equals($_SESSION['csrf'], $token)) {
        http_response_code(403);
        $status = "Reload the page and try again.";
    } elseif (!validMailInput($subject, $body)) {
        http_response_code(422);
        $status = "Check the subject and body.";
    } elseif (time() - ($_SESSION['attempt'] ?? 0) < 60) {
        http_response_code(429);
        $status = "Wait 60 seconds before trying again.";
    } else {
        $_SESSION['attempt'] = time();
        try {
            sendDemoMail($subject, $body, true);
            $_SESSION['notice'] = "Message captured locally.";
            $_SESSION['csrf'] = bin2hex(random_bytes(32));
            header('Location: form.php', true, 303);
            exit;
        } catch (Throwable $error) {
            http_response_code(502);
            $status = "Local SMTP capture failed.";
        }
    }
} elseif ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    header('Allow: GET, POST');
    http_response_code(405);
    exit;
}

function h(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Local mail capture</title>
</head>
<body>
  <h1>Local mail capture</h1>
  <?php if ($status !== ''): ?>
    <p role="status"><?= h($status) ?></p>
  <?php endif; ?>
  <form method="post" action="form.php">
    <input type="hidden" name="csrf" value="<?= h($_SESSION['csrf']) ?>">
    <p><label>Subject <input name="subject" required></label></p>
    <p><label>Message <textarea name="body" required></textarea></label></p>
    <button type="submit">Capture a test message</button>
  </form>
</body>
</html>
php -S 127.0.0.1:8080 -t public

The subject and body limits are 300 and 10,000 bytes. A valid submission redirects with 303 and shows the status. Invalid tokens produce 403, invalid input 422, and a repeat within 60 seconds 429. Keep this form and PHP development server local. For a public service, design authentication and authorization, server-wide limits, duplicate prevention, and session settings suitable for HTTPS.

Check Gmail and Microsoft 365 authentication

Consider OAuth for Gmail. The Google app password guide requires 2-Step Verification for app passwords and lists account restrictions. This article’s password path applies to accounts where that sign-in method is permitted.

For Microsoft 365, check SMTP AUTH settings for the tenant and mailbox. The Microsoft SMTP OAuth guide covers application registration, access tokens, and XOAUTH2. Setting SMTPAuth to true enables authentication but does not configure OAuth tokens. Use the authentication flow supported by the provider.

Diagnose submission and delivery separately

For timeouts, check the host and port, DNS, and any outbound SMTP restrictions. For TLS errors, check the port and TLS mode, certificate hostname, and trusted CA certificates. For authentication failures, verify account policy, credentials, and permissions for the From address.

A successful send() means the SMTP server accepted the message. For non-delivery, check the provider’s event log, bounces, spam classification, and your domain’s SPF, DKIM, and DMARC settings. The PHPMailer troubleshooting guide explains SMTPDebug. Use it briefly in a restricted test environment and keep logs that could contain addresses or message content private.