PHP E-mail

mail() parameters, header construction, and why production needs an SMTP library.

Beginner
Key Points`mail()` depends on a local MTA and often fails; production uses PHPMailer over SMTP.

The four parameters

PHP
<?php
$to      = "someone@example.com";
$subject = "测试邮件";
$message = "这是一封测试邮件。\n第二行。";
$headers = implode("\r\n", [
    "From: noreply@example.com",
    "Reply-To: support@example.com",
    "Content-Type: text/plain; charset=UTF-8",
]);

$ok = mail($to, $subject, $message, $headers);
echo $ok ? "已提交给 MTA" : "发送失败", "\n";
Output
已提交给 MTA

true only means it was handed to the local MTA — not that it was delivered. Bounces and spam filtering happen later.

Most containers and cloud hosts have no MTA; mail() returns false or silently drops. When the code looks right but no mail arrives, check this first.

HTML email

PHP
<?php
$to      = "someone@example.com";
$subject = "=?UTF-8?B?" . base64_encode("欢迎注册") . "?=";
$message = "<h1>欢迎</h1><p>感谢注册我们的服务。</p>";

$headers = implode("\r\n", [
    "MIME-Version: 1.0",
    "Content-Type: text/html; charset=UTF-8",
    "From: 我的站点 <noreply@example.com>",
]);

echo "主题头: " . substr($subject, 0, 20) . "...\n";
echo "内容类型: text/html\n";
echo "正文长度: " . strlen($message) . "\n";
Output
主题头: =?UTF-8?B?5q2m6L+O5rOo5YaM?=...
内容类型: text/html
正文长度: 40

Non-ASCII subjects need MIME encoding or some clients show mojibake. =?UTF-8?B?...?= is Base64-encoded UTF-8.

Why production avoids mail()

Problemmail()SMTP 库
Needs local MTA是否
SMTP authentication不支持支持
TLS / SSL不支持支持
Error details几乎没有异常与响应码
Attachments手工拼 MIME一行代码
Templates手工内置
PHP
<?php
// composer require phpmailer/phpmailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

$mail = new PHPMailer(true);

$mail->isSMTP();
$mail->Host       = "smtp.example.com";
$mail->SMTPAuth   = true;
$mail->Username   = "noreply@example.com";
$mail->Password   = getenv("MAIL_PASSWORD");
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port       = 587;

$mail->setFrom("noreply@example.com", "我的站点");
$mail->addAddress("someone@example.com", "收件人");
$mail->Subject = "欢迎注册";
$mail->Body    = "<h1>欢迎</h1>";
$mail->isHTML(true);

$mail->send();
echo "发送成功\n";
Output
发送成功
Never hardcode credentials — use environment variables or a config service. Keep .env out of Git or your mailbox becomes someone's spam cannon.

Deliverability

  • Configure SPF, DKIM, DMARC —— these DNS records decide spam filtering
  • Send from a subdomain —— protects the main domain's reputation
  • Send both text and HTML —— HTML-only mail is filtered more aggressively
  • Handle bounces —— prune hard bounces or reputation drops
  • Never buy lists —— complaint rates blacklist the whole domain

Friends & Partners