萬盛學電腦網

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

PHP mail() 函數寄送郵件完整指南:基本用法、HTML 郵件、表單整合與安全考量

PHP mail() 函數提供基本郵件發送功能,但需正確配置伺服器 MTA (Mail Transfer Agent) 才能運作。本文涵蓋語法參數、純文字/HTML 郵件、表單整合、標頭注入防護、現代替代方案建議。

基本語法與參數

<?php
mail(
    string $to,           // 收件者:'user@example.com' 或 'Name <user@example.com>'
    string $subject,      // 主旨 (不可含換行)
    string $message,      // 郵件內容,每行 < 70 字元,\n 換行
    array|string $additional_headers = [], // 額外標頭:From, Cc, Bcc, Reply-To 等
    string $additional_params = ""         // 額外傳給 sendmail 的參數
): bool

最簡單純文字郵件

<?php
$to = 'recipient@example.com';
$subject = 'Test Mail';
$message = "Hello!\nThis is a simple email message.\nSent from PHP.";
$headers = 'From: sender@example.com';

if (mail($to, $subject, $message, $headers)) {
    echo "Mail sent successfully.";
} else {
    echo "Mail sending failed.";
}
?>

HTML 格式郵件

<?php
$to = 'recipient@example.com';
$subject = 'HTML Email Test';
$message = '
<html>
<body>
    <h1 style="color: #333;">Welcome!</h1>
    <p>This is an <strong>HTML</strong> email.</p>
    <p><a href="https://example.com">Visit our site</a></p>
</body>
</html>
';

// 關鍵:MIME-Version 與 Content-Type 標頭
$headers = [
    'MIME-Version: 1.0',
    'Content-type: text/html; charset=UTF-8',
    'From: Sender Name <sender@example.com>',
    'Reply-To: reply@example.com',
    'X-Mailer: PHP/' . phpversion(),
];

mail($to, $subject, $message, implode("\r\n", $headers));
?>

多部分郵件:HTML + 純文字備選

<?php
$to = 'recipient@example.com';
$subject = 'Multipart Email';

$textContent = "Hello!\nThis is plain text version.\nVisit: https://example.com";
$htmlContent = '
<html><body>
    <h1>Hello!</h1>
    <p>This is <strong>HTML</strong> version.</p>
    <p><a href="https://example.com">Visit our site</a></p>
</body></html>
';

$boundary = md5(time()); // 隨機邊界字串

$headers = [
    'MIME-Version: 1.0',
    "Content-Type: multipart/alternative; boundary=\"$boundary\"",
    'From: Sender <sender@example.com>',
];

$message = "--$boundary\r\n";
$message .= "Content-Type: text/plain; charset=UTF-8\r\n";
$message .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
$message .= $textContent . "\r\n\r\n";

$message .= "--$boundary\r\n";
$message .= "Content-Type: text/html; charset=UTF-8\r\n";
$message .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
$message .= $htmlContent . "\r\n\r\n";

$message .= "--$boundary--\r\n";

mail($to, $subject, $message, implode("\r\n", $headers));
?>

郵件表單整合(聯絡表單)

<?php
// contact.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF 驗證...
    
    $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    $subject = filter_input(INPUT_POST, 'subject', FILTER_SANITIZE_SPECIAL_CHARS);
    $message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_SPECIAL_CHARS);
    
    $errors = [];
    if (!$email) $errors[] = '有效 Email 為必填';
    if (!$subject) $errors[] = '主旨為必填';
    if (!$message) $errors[] = '內容為必填';
    
    if ($errors) {
        // 回傳錯誤...
    } else {
        $headers = [
            'From: ' . $email,
            'Reply-To: ' . $email,
            'X-Mailer: PHP/' . phpversion(),
        ];
        
        $body = "From: $email\nSubject: $subject\n\n$message";
        
        if (mail('admin@example.com', "Contact Form: $subject", $body, implode("\r\n", $headers))) {
            echo "感謝您的來信,我們會盡快回覆。";
        } else {
            echo "發送失敗,請稍後再試。";
        }
    }
}
?>

<form method="post">
    <input type="email" name="email" placeholder="Your Email" required /><br>
    <input type="text" name="subject" placeholder="Subject" required /><br>
    <textarea name="message" rows="10" cols="40" placeholder="Message" required></textarea><br>
    <input type="submit" value="送出" />
</form>

關鍵安全議題:標頭注入攻擊

🔴 高風險: 若用戶輸入含換行符 \r\n 注入額外標頭 (如 Bcc: attacker@evil.com),可濫發垃圾郵件。

防護措施

<?php
function sanitizeHeader(string $value): string {
    // 移除換行符
    return str_replace(["\r", "\n"], ['', ''], $value);
}

$safeSubject = sanitizeHeader($_POST['subject'] ?? '');
$safeFrom = sanitizeHeader($_POST['email'] ?? '');

// 額外驗證 Email 格式
if (!filter_var($safeFrom, FILTER_VALIDATE_EMAIL)) {
    die('Invalid email');
}

$headers = [
    'From: ' . $safeFrom,
    'Reply-To: ' . $safeFrom,
];
?>

mail() 限制與現代替代方案

限制說明解決方案
依賴本地 MTA需配置 sendmail/postfix/exim,Windows 環境複雜使用 SMTP 函數庫
無認證機制易被標記垃圾郵件、無法經過驗證發送SMTP 認證 (SPF/DKIM/DMARC)
無連線池/重試大量發送效能差、失敗無重試隊列 + 背景任務
無附件/內嵌圖片支援需手動構建 MIME函數庫自動處理
難以除錯/追蹤無發送日誌、退信處理專用郵件服務 API

推薦:PHPMailer / Symfony Mailer

<?php
// Composer: 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 = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your@gmail.com';
    $mail->Password = 'app_password'; // 應用程式密碼
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;
    
    $mail->setFrom('your@gmail.com', 'Your Name');
    $mail->addAddress('recipient@example.com');
    $mail->addReplyTo('reply@example.com');
    
    $mail->isHTML(true);
    $mail->Subject = 'PHPMailer Test';
    $mail->Body = '<h1>Hello!</h1><p>HTML content</p>';
    $mail->AltBody = 'Plain text version';
    
    $mail->send();
    echo 'Message sent';
} catch (Exception $e) {
    echo "Mailer Error: {$mail->ErrorInfo}";
}
?>

專用郵件服務 API (更推薦生產環境)

  • SendGrid:API 發送、模板、統計、Webhook
  • Mailgun:強大 API、路由、驗證
  • Amazon SES:低成本、高投遞率、需配置 DKIM
  • Postmark:專注交易郵件、極速投遞
<?php
// SendGrid 範例
$email = new \SendGrid\Mail\Mail();
$email->setFrom("sender@example.com", "Sender Name");
$email->setSubject("Subject");
$email->addTo("recipient@example.com", "Recipient");
$email->addContent("text/html", "<strong>HTML content</strong>");

$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
$response = $sendgrid->send($email);
?>
💡 架構建議: 發送郵件非同步化。控制器只將郵件任務推入隊列 (Redis/RabbitMQ/DB),背景 Worker (Supervisor/Horizon) 處理實際發送。避免 HTTP 請求阻塞、失敗可重試、支援批次發送。
copyright © 萬盛學電腦網 all rights reserved