在開發專案時,常需發送電子郵件。許多開發者習慣使用第三方郵件服務(如 Gmail、QQ 郵箱),但客戶不一定願意提供發件帳號密碼。此時,PHP 內建的 mail() 函數配合 sendmail 即可在本地實現郵件發送,無需依賴外部 SMTP 服務商帳號。
sendmail.zip,解壓至任意目錄(例如 D:/sendmail)。[sendmail]
smtp_server=smtp.qq.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=your_email@qq.com
auth_password=your_password
force_sender=your_email@qq.com
[mail function] 區段設定:
[mail function]
SMTP = smtp.qq.com
smtp_port = 25
sendmail_from = your_email@qq.com
sendmail_path = "D:/sendmail/sendmail.exe -t -i"
mail.add_x_header = On
注意:實測 QQ 郵箱發送成功,163 郵箱可能因反垃圾機制失敗,Gmail 可正常接收。
mail(string $to, string $subject, string $message, array|string $headers = [], string $parameters = ""): bool
true,否則 false。接受不代表送達。$message 中各行必須以 LF (\n) 分隔,單行不超過 70 字元。$text = str_replace("\n.", "\n..", $text);
<?php
$to = "user1@example.com, user2@example.com";
$subject = "HTML 郵件測試";
$message = "
<html>
<head>
<title>HTML 郵件</title>
</head>
<body>
<p>這是包含 HTML 標籤的郵件!</p>
<table>
<tr><th>姓</th><th>名</th></tr>
<tr><td>John</td><td>Doe</td></tr>
</table>
</body>
</html>
";
// 設定標頭
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$headers .= "From: <webmaster@example.com>\r\n";
$headers .= "Cc: myboss@example.com\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "郵件已提交發送系統";
} else {
echo "郵件提交失敗";
}
?>
smtp_port 與 SMTPSecure。auth_username/auth_password 正確,且開啟「授權碼」而非登入密碼。掌握 mail() 與 sendmail 配置,即可在不依賴第三方帳號的情況下實現伺服器端郵件發送,適合內部通知、驗證碼等場景。