PHP 內建 mail() 函數讓開發者能直接從腳本發送電子郵件,是網站聯絡表單、通知系統、密碼重設等功能的基礎組件。本文涵蓋語法詳解、基本用法、表單整合與注意事項。
mail(to, subject, message, headers, parameters)
| 參數 | 必要性 | 說明 |
|---|---|---|
| to | 必需 | 收件者郵件地址,多個地址以逗號分隔 |
| subject | 必需 | 郵件主題,不可包含換行字符 |
| message | 必需 | 郵件內容,行與行之間用 LF (\n) 分隔,每行限制 70 字符 |
| headers | 可選 | 額外標頭(From、Cc、Bcc 等),用 CRLF (\r\n) 分隔 |
| parameters | 可選 | 傳遞給郵件發送程式的額外參數 |
系統需求:伺服器需安裝並啟動郵件系統(sendmail、postfix、qmail 等),並在 php.ini 中正確配置。
<?php
$to = "recipient@example.com";
$subject = "測試郵件主題";
$message = "Hello!\n這是郵件內容。\n支援多行文字。";
$from = "sender@example.com";
$headers = "From: $from\r\n";
$headers .= "Reply-To: $from\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();
if (mail($to, $subject, $message, $headers)) {
echo "郵件已發送";
} else {
echo "郵件發送失敗";
}
?>
完整的 HTML 表單與 PHP 處理邏輯整合:
<html>
<head>
<meta charset="utf-8">
<title>聯絡我們</title>
</head>
<body>
<?php
if (isset($_REQUEST['email'])) {
// 發送郵件邏輯
$email = $_REQUEST['email'];
$subject = $_REQUEST['subject'];
$message = $_REQUEST['message'];
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if (mail("admin@example.com", $subject, $message, $headers)) {
echo "<p style='color:green'>郵件發送成功!我們會盡快回覆。</p>";
} else {
echo "<p style='color:red'>郵件發送失敗,請稍後再試。</p>";
}
} else {
?>
<form method="post" action="">
<label>您的 Email:<br>
<input type="email" name="email" required></label><br><br>
<label>主旨:<br>
<input type="text" name="subject" required></label><br><br>
<label>內容:<br>
<textarea name="message" rows="10" cols="50" required></textarea></label><br><br>
<input type="submit" value="送出">
</form>
<?php } ?>
</body>
</html>
上述簡易範例存在安全風險! 直接使用使用者輸入構建郵件標頭易導致 Header Injection 攻擊。生產環境必須:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@gmail.com';
$mail->Password = 'your_app_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('your@gmail.com', '您的名稱');
$mail->addAddress('recipient@example.com');
$mail->Subject = 'PHPMailer 測試';
$mail->Body = '這是使用 PHPMailer 發送的測試郵件。';
$mail->CharSet = 'UTF-8';
$mail->send();
echo '郵件發送成功';
} catch (Exception $e) {
echo "郵件發送失敗: {$mail->ErrorInfo}";
}
?>
php.ini [mail function] 設定;確認防火牆開放 25/465/587 埠CharSet = 'UTF-8'掌握 PHP 郵件發送不僅是語法熟悉度,更包含安全意識、送達率優化與架構設計。建議新專案直接採用 PHPMailer 等成熟方案,專注於業務邏輯開發。