在 PHP 中用 PHPMailer 通过 SMTP 发送邮件

在 PHP 中通过简单邮件传输协议(SMTP)提交邮件,需要安装 PHPMailer 并配置服务器、端口、TLS 加密方式和凭据。先用本地邮件捕获工具核对主题与正文,再接入邮件服务商。

安装 PHPMailer 并准备文件

准备 PHP 8.3 和 Composer。通过 TLS 连接需要启用 PHP 的 OpenSSL 扩展。在项目目录安装依赖时执行 Composer 的 require 命令,生成 vendor/autoload.php。

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

将下面的文件保存在同一项目中。示例已在 PHP 8.3.32 和 PHPMailer 7.4.1 上验证。服务器无法运行 Composer 时,可事先安装好依赖并一同部署,也可按 PHPMailer 官方仓库 的说明手动加载。表单的 Web 文档根目录设为 public。

在本地捕获 UTF-8 邮件

启动 Mailpit 安装指南中的工具,将 SMTP 绑定到 127.0.0.1:1025,列表页面绑定到 127.0.0.1:8025。保持转发与中继关闭。保存下面的两个 PHP 文件并运行 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

默认模式是 capture。本地服务器接收后,命令行会显示 Accepted by the SMTP server. 在 Mailpit 中确认主题为 SMTP test – café,正文含有 café / 한글 以及换行。CharSet 属性指定 UTF-8。非加密模式只用于这个回环地址。

配置 TLS 与实际发信凭据

按服务商说明选择 Host、Port 和 SMTPSecure。RFC 8314 所述的 STARTTLS 先建立连接再升级到 TLS,通常用 587。SMTPS 从连接开始就使用 TLS,通常用 465。请将示例值换成有发信权限的账号设置。

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

运行 php send.php send 才会连到配置的实际 SMTP 服务器。通过部署环境的密钥配置传入密码,并确认 FPM 或 Apache 的 PHP 进程能读取。使用服务商允许的发件地址或别名,收件地址由服务器配置决定。表单收集的访客邮箱经过验证后可用于 Reply-To。发送 HTML 邮件时请在 AltBody 提供纯文本版本。

用固定收件人测试本地表单

将表单保存为 public/form.php,启动 PHP 开发服务器,然后访问 http://127.0.0.1:8080/form.php。表单只向本地捕获服务器提交。会话令牌用于防止跨站请求伪造(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 = "请重新加载页面后再试。";
    } elseif (!validMailInput($subject, $body)) {
        http_response_code(422);
        $status = "请检查主题和正文。";
    } elseif (time() - ($_SESSION['attempt'] ?? 0) < 60) {
        http_response_code(429);
        $status = "请等待 60 秒后再试。";
    } else {
        $_SESSION['attempt'] = time();
        try {
            sendDemoMail($subject, $body, true);
            $_SESSION['notice'] = "已在本地接收邮件。";
            $_SESSION['csrf'] = bin2hex(random_bytes(32));
            header('Location: form.php', true, 303);
            exit;
        } catch (Throwable $error) {
            http_response_code(502);
            $status = "本地 SMTP 捕获失败。";
        }
    }
} 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="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>本地邮件捕获</title>
</head>
<body>
  <h1>本地邮件捕获</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>主题 <input name="subject" required></label></p>
    <p><label>正文 <textarea name="body" required></textarea></label></p>
    <button type="submit">捕获测试邮件</button>
  </form>
</body>
</html>
php -S 127.0.0.1:8080 -t public

主题最多 300 字节,正文最多 10,000 字节。提交成功时 303 重定向并显示状态。令牌错误返回 403,输入无效返回 422,60 秒内重试返回 429。这个表单和开发服务器用于本地测试。对外服务需要单独设计认证授权、全局限流、防重复提交和适合 HTTPS 的会话设置。

核对 Gmail 和 Microsoft 365 的认证方式

Gmail 建议先考虑 OAuth。Google 应用专用密码指南 说明应用专用密码需要开启两步验证,并列出了账户限制。仅在账户允许时才使用本文的密码认证路径。

使用 Microsoft 365 时,请检查租户和邮箱的 SMTP AUTH 设置。Microsoft 的 SMTP OAuth 文档 介绍应用注册、访问令牌和 XOAUTH2。打开 SMTPAuth 只是启用认证,OAuth 令牌需要按服务商要求另行配置。

区分提交错误与投递问题

连接超时时检查主机名、端口、DNS 和 SMTP 出站限制。TLS 出错时检查端口和加密方式、证书主机名及受信任的 CA。认证被拒绝时核对账户策略、凭据及发件地址权限。

send() 成功表示 SMTP 服务器已经接收邮件。若邮件未投递,请查看服务商事件记录、退信、垃圾邮件分类及域名的 SPF、DKIM 和 DMARC。PHPMailer 故障排查指南介绍了 SMTPDebug。只在访问受限的测试环境中短时开启,含邮箱地址或正文的日志应保密。