萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 表單提交發送郵件入門範例

前言

最基礎的 PHP 表單發送郵件流程:HTML 表單收集資料 → POST 到 PHP 腳本 → mail() 函數發送。本文提供最精簡可用的入門範例,適合初學者理解基本流程。

HTML 表單

<!-- 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 處理腳本

<?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>";
?>

關鍵點說明

  1. mail() 參數順序:to, subject, message, additional_headers。
  2. Header 之間用 \r\n 分隔 (RFC 規範),最後不需額外換行。
  3. Content-Type: text/plain; charset=UTF-8 確保中文正常顯示。
  4. 返回值 true 代表「已交給本地郵件傳輸代理 (MTA)」,不保證送達。

本地測試環境配置

  • Linux/macOS:安裝 Postfix sudo apt install postfix (選 Internet Site),測試 echo "test" | mail -s "test" user@example.com。
  • Windows:PHP 內建 mail 不支援 SMTP 直連,需配置 php.ini SMTP=smtp.gmail.com smtp_port=587 sendmail_from=you@gmail.com,但 Gmail 需 OAuth2,建議直接用 PHPMailer 走 SMTP。
  • Docker:使用 namshi/smtp 或 mailhog 捕獲測試郵件。

進階學習路徑

掌握基礎後,建議依序學習:

  1. HTML 郵件 (multipart/alternative)
  2. 附件發送 (multipart/mixed)
  3. PHPMailer / Symfony Mailer 封裝庫
  4. SMTP 認證、STARTTLS、DKIM 簽名
  5. 郵件隊列 (Laravel Queue, Symfony Messenger)
  6. 退信處理、打開率追蹤、退訂機制
copyright © 萬盛學電腦網 all rights reserved