最基礎的 PHP 表單發送郵件流程:HTML 表單收集資料 → POST 到 PHP 腳本 → mail() 函數發送。本文提供最精簡可用的入門範例,適合初學者理解基本流程。
<!-- email.html -->
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>簡易發送郵件</title></head>
<body>
<h1>郵件表單</h1>
<form method="post" action="mail.php">
<div>
<label>收件人:</label>
<input type="email" name="mailto" required>
</div>
<div>
<label>主旨:</label>
<input type="text" name="mailsubject" required>
</div>
<div>
<label>內容:</label><br/>
<textarea name="mailbody" rows="8" cols="50" required></textarea>
</div>
<button type="submit">發送</button>
</form>
</body>
</html>
<?php
// mail.php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: email.html');
exit;
}
$to = trim($_POST['mailto'] ?? '');
$subject = trim($_POST['mailsubject'] ?? '');
$body = $_POST['mailbody'] ?? '';
if (!$to) die('收件人不能為空');
if (!$subject) $subject = '(無主旨)';
if (!$body) $body = '(無內容)';
// 簡單 Header
$headers = "From: noreply@example.com\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
$result = mail($to, $subject, $body, $headers);
if ($result) {
echo "<p style='color:green'>郵件已提交給郵件伺服器!</p>";
} else {
echo "<p style='color:red'>郵件提交失敗,請檢查伺服器配置。</p>";
}
echo "<a href='email.html'>返回表單</a>";
?>
mail() 參數順序:to, subject, message, additional_headers。\r\n 分隔 (RFC 規範),最後不需額外換行。Content-Type: text/plain; charset=UTF-8 確保中文正常顯示。true 代表「已交給本地郵件傳輸代理 (MTA)」,不保證送達。sudo apt install postfix (選 Internet Site),測試 echo "test" | mail -s "test" user@example.com。php.ini SMTP=smtp.gmail.com smtp_port=587 sendmail_from=you@gmail.com,但 Gmail 需 OAuth2,建議直接用 PHPMailer 走 SMTP。namshi/smtp 或 mailhog 捕獲測試郵件。掌握基礎後,建議依序學習: