不依賴第三方庫(如 PHPMailer),直接使用 mail() 構建 multipart/mixed MIME 郵件,支援文字內容與 Base64 編碼附件。
<form method="post" action="sendmail.php" enctype="multipart/form-data"> 寄件者:<input type="email" name="from" required><br> 收件者:<input type="email" name="to" required><br> 主旨:<input type="text" name="subject"><br> 內容:<textarea name="body"></textarea><br> 附件:<input type="file" name="upload_file"><br> <input type="submit" value="發送"> </form>
sendmail.php<?php
$from = $_POST['from'];
$to = $_POST['to'];
$subject = $_POST['subject'];
$body = $_POST['body'];
// 邊界字串(需唯一,通常用 hash 或隨機字串)
$boundary = md5(time());
// Header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";
$headers .= "From: $from\r\n";
// 讀取上傳檔案
$fileTmp = $_FILES['upload_file']['tmp_name'];
$fileName = $_FILES['upload_file']['name'];
$mimeType = $_FILES['upload_file']['type'] ?: 'application/octet-stream';
$fileContent = '';
if (is_uploaded_file($fileTmp)) {
$content = file_get_contents($fileTmp);
$fileContent = chunk_split(base64_encode($content));
}
// 組裝郵件主體
$message = "--$boundary\r\n";
$message .= "Content-Type: text/plain; charset=utf-8\r\n";
$message .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
$message .= "$body\r\n";
$message .= "--$boundary\r\n";
$message .= "Content-Type: $mimeType; name=\"$fileName\"\r\n";
$message .= "Content-Disposition: attachment; filename=\"$fileName\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n\r\n";
$message .= "$fileContent\r\n";
$message .= "--$boundary--\r\n";
// 發送
if (mail($to, $subject, $message, $headers)) {
echo "郵件發送成功";
} else {
echo "郵件發送失敗,請檢查 mail log";
}
?>
boundary 不可包含在內容中,使用 md5(time()) 產生唯一值。--$boundary 開頭,結尾以 --$boundary-- 結束。base64_encode 後再 chunk_split(每 76 字元換行,符合 MIME 標準)。mail() 依賴本地 MTA(Postfix/Sendmail),確保伺服器已正確設定寄信服務。