首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP mail() 函數完整配置與使用指南(Windows 環境)

     編輯:PHP 相關知識

在開發專案時,常需發送電子郵件。許多開發者習慣使用第三方郵件服務(如 Gmail、QQ 郵箱),但客戶不一定願意提供發件帳號密碼。此時,PHP 內建的 mail() 函數配合 sendmail 即可在本地實現郵件發送,無需依賴外部 SMTP 服務商帳號。

一、Windows 環境下配置 sendmail

  1. 下載並解壓:取得 sendmail.zip,解壓至任意目錄(例如 D:/sendmail)。
  2. 修改 sendmail.ini:根據實際需求調整以下參數:
    [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
  3. 修改 php.ini:在 [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
  4. 重啟 Web 服務器(Apache/Nginx)使配置生效。
注意:實測 QQ 郵箱發送成功,163 郵箱可能因反垃圾機制失敗,Gmail 可正常接收。

二、mail() 函數語法與關鍵說明

mail(string $to, string $subject, string $message, array|string $headers = [], string $parameters = ""): bool
  • 回傳值:郵件被發送系統接受返回 true,否則 false。接受不代表送達。
  • 訊息格式:$message 中各行必須以 LF (\n) 分隔,單行不超過 70 字元。
  • Windows 下的句點問題:行首若為句點會被移除,需預先替換:
    $text = str_replace("\n.", "\n..", $text);

三、發送 HTML 郵件完整範例

<?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 "郵件提交失敗";
}
?>

四、常見問題排查

  • 端口 25 被封鎖:嘗試 465 (SSL) 或 587 (TLS) 端口,並相應修改 smtp_port 與 SMTPSecure。
  • 認證失敗:確認 auth_username/auth_password 正確,且開啟「授權碼」而非登入密碼。
  • 郵件進垃圾箱:設定 SPF、DKIM、DMARC 記錄;避免標題/內容含敏感詞。

掌握 mail() 與 sendmail 配置,即可在不依賴第三方帳號的情況下實現伺服器端郵件發送,適合內部通知、驗證碼等場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved