Inviare email SMTP in PHP con PHPMailer

Per inviare email da PHP tramite il Simple Mail Transfer Protocol (SMTP), installa PHPMailer e configura il server, la porta, la modalità TLS e le credenziali. Prima di usare il provider, verifica oggetto e corpo con un ricevitore locale.

Installare PHPMailer e preparare i file

Installa PHP 8.3 e Composer. Abilita l’estensione OpenSSL di PHP per le connessioni TLS. Esegui il comando require di Composer nella directory del progetto per generare vendor/autoload.php.

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

Salva i file nel progetto. Gli esempi sono stati verificati con PHP 8.3.32 e PHPMailer 7.4.1. Se Composer non è disponibile sul server, prepara le dipendenze altrove oppure segui il caricamento manuale indicato nel repository di PHPMailer. Usa public come radice web del modulo locale.

Catturare un messaggio UTF-8 in locale

Avvia il programma indicato nella guida di installazione di Mailpit con SMTP su 127.0.0.1:1025 e la lista dei messaggi su 127.0.0.1:8025. Lascia disattivati inoltro e relay. Salva entrambi i file PHP e avvia 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

La modalità predefinita è capture. Quando il server locale accetta il messaggio, lo script stampa Accepted by the SMTP server. Controlla in Mailpit l’oggetto SMTP test – café e il corpo con café / 한글 e un ritorno a capo. CharSet imposta UTF-8. Il percorso senza cifratura resta limitato alla connessione di loopback.

Configurare TLS e credenziali di invio

Controlla la combinazione di Host, Port e SMTPSecure prevista dal provider. In RFC 8314, STARTTLS attiva TLS su una connessione già aperta, spesso sulla porta 587. SMTPS usa TLS dall’inizio, in genere sulla 465. Sostituisci i dati di esempio con quelli di un account autorizzato.

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

Usa php send.php send per il server configurato. Passa la password tramite la gestione dei segreti e verifica che raggiunga il processo PHP con FPM o Apache. Usa un mittente o un alias approvato e fissa il destinatario lato server. Un indirizzo del visitatore, dopo la validazione, può essere inserito in Reply-To. Per HTML, configura un testo alternativo in AltBody.

Provare un modulo locale con destinatario fisso

Salva il modulo come public/form.php, avvia il server di sviluppo e apri http://127.0.0.1:8080/form.php. Il modulo invia solo al ricevitore locale. Un token di sessione protegge dalla falsificazione di richieste tra siti (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 = "Ricarica la pagina e riprova.";
    } elseif (!validMailInput($subject, $body)) {
        http_response_code(422);
        $status = "Controlla oggetto e corpo del messaggio.";
    } elseif (time() - ($_SESSION['attempt'] ?? 0) < 60) {
        http_response_code(429);
        $status = "Attendi 60 secondi prima di riprovare.";
    } else {
        $_SESSION['attempt'] = time();
        try {
            sendDemoMail($subject, $body, true);
            $_SESSION['notice'] = "Messaggio acquisito in locale.";
            $_SESSION['csrf'] = bin2hex(random_bytes(32));
            header('Location: form.php', true, 303);
            exit;
        } catch (Throwable $error) {
            http_response_code(502);
            $status = "Acquisizione SMTP locale non riuscita.";
        }
    }
} 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="it">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Acquisizione locale di email</title>
</head>
<body>
  <h1>Acquisizione locale di email</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>Oggetto <input name="subject" required></label></p>
    <p><label>Messaggio <textarea name="body" required></textarea></label></p>
    <button type="submit">Acquisisci un messaggio di prova</button>
  </form>
</body>
</html>
php -S 127.0.0.1:8080 -t public

I limiti sono di 300 byte per l’oggetto e 10.000 per il corpo. Un invio valido reindirizza con 303 e mostra lo stato. Un token errato restituisce 403, un input non valido 422, un tentativo entro 60 secondi 429. Usa questo modulo solo in locale. Per un servizio pubblico occorrono autenticazione, autorizzazioni, limiti sul server, prevenzione dei duplicati e sessioni configurate per HTTPS.

Verificare l’autenticazione Gmail e Microsoft 365

Per Gmail valuta OAuth. La guida di Google alle password per le app richiede la verifica in due passaggi per le password per le app e descrive le restrizioni. Usa il percorso con password solo se l’account lo consente.

Per Microsoft 365 verifica SMTP AUTH per il tenant e la casella. La guida Microsoft a OAuth per SMTP descrive la registrazione dell’applicazione, i token di accesso e XOAUTH2. SMTPAuth abilita l’autenticazione. I token OAuth si configurano separatamente secondo le istruzioni del provider.

Distinguere problemi di invio e di consegna

In caso di timeout, controlla host, porta, DNS e restrizioni SMTP in uscita. Per gli errori TLS verifica modalità, porta, nome del certificato e CA attendibili. Se l’autenticazione viene rifiutata, controlla credenziali, criteri dell’account e permessi del mittente.

Il successo di send() indica che il server SMTP ha accettato il messaggio. In caso di mancata consegna, consulta gli eventi del provider, i messaggi di rimbalzo, i filtri antispam e SPF, DKIM e DMARC del dominio. La guida alla risoluzione dei problemi di PHPMailer spiega SMTPDebug. Attivalo brevemente in un ambiente ristretto e proteggi i log con indirizzi o contenuti.