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