Windows 環境下 PHP mail() 預設需配置 SMTP 伺服器。常見公共 SMTP (163, Sina 等) 禁止匿名轉發。解決方案:本機架設 **Imail SMTP 服務** (或 hMailServer、Postfix for Windows) 作為本地轉發郵件伺服器。
SERVER)。; php.ini
SMTP = localhost ; 或 127.0.0.1,指向本機 Imail
smtp_port = 25
; sendmail_from = noreply@example.com ; 可選,預設寄件者
<?php
$to = 'target@example.com';
$subject = '測試 Imail 發送';
$message = '<h1>HTML 郵件測試</h1><p>包含圖片:<img src="https://example.com/logo.png"></p>';
$headers = [
'From: sender@example.com',
'Content-Type: text/html; charset=UTF-8',
'Content-Transfer-Encoding: 8bit',
'X-Mailer: PHP/' . PHP_VERSION,
];
$result = mail($to, $subject, $message, implode("\r\n", $headers));
var_dump($result); // true/false
?>
mail() 功能極簡:無 SMTP AUTH、無 TLS、無附件支援、錯誤處理弱、編碼易出錯。
<?php
// composer require phpmailer/phpmailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'localhost'; // Imail 本機
$mail->Port = 25; // 或 587 (STARTTLS)
$mail->SMTPAuth = false; // Imail 若設定允許本機免認證
// $mail->Username = 'user';
// $mail->Password = 'pass';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 若啟用 TLS
$mail->setFrom('noreply@example.com', '系統通知');
$mail->addAddress('target@example.com');
$mail->isHTML(true);
$mail->Subject = '測試 PHPMailer + Imail';
$mail->Body = 'HTML 內容
支援附件、內嵌圖片、多收件人、優雅錯誤處理
';
$mail->AltBody = '純文本備用內容';
$mail->send();
echo '發送成功';
} catch (Exception $e) {
echo "發送失敗: {$mail->ErrorInfo}";
}
?>
Imail 為商業軟體且已停止更新。**強烈建議改用 hMailServer** (Windows 原生、支援 IMAP/POP3/SMTP、WebAdmin、DKIM、防毒整合、資料庫後端)。安裝精靈化,配置圖形化,文檔完善。
Windows + PHP 發送郵件,**本地 SMTP 服務 (Imail/hMailServer) + PHPMailer/Symfony Mailer** 是穩健組合。棄用 mail()、配置認證加密、設定 DKIM/SPF/DMARC、監控發送佇列與退信,才能構建可靠的郵件發送系統。