展示如何使用 mime_mail 類別發送包含附件(GIF 圖片)的中文郵件,並包含基本的 Referer 檢查與郵箱格式驗證。
<?php
// 防止跨站濫用:檢查 Referer 來源與郵箱格式
if (!preg_match("!^(https://)?".getenv("SERVER_NAME")."!", getenv("HTTP_REFERER")) ||
!preg_match("/^.+@.+\..+/", $myemail)) {
echo " ";
} else {
include "mime_mail.inc";
$filename = "php_logo.gif";
$content_type = "image/gif";
// 讀取附件二進位內容
$fd = fopen($filename, "r");
$data = fread($fd, filesize($filename));
fclose($fd);
// 建立郵件物件
$mail = new mime_mail;
$mail->from = $myemail;
$mail->to = $myemail;
$mail->subject = "歡迎!";
$mail->body = "這是真正的電子郵件訊息,當然....你可以寫成一行以上。";
// 加入附件
$mail->add_attachment($data, $filename, $content_type);
// 發送
$mail->send();
echo "郵件已送出,請檢查您的信箱。";
}
?>
fread() 讀取二進位檔案,傳給 add_attachment() 時需指定正確 MIME 類型。send() 回傳值,生產環境需加入 try-catch 或回傳值判斷。核心方法:
add_attachment($data, $name, $ctype):加入附件或內文(內文以 text/plain 加入)build_multipart():構建 multipart/mixed MIME 結構,產生邊界字串get_mail():組裝完整郵件標頭與內文send():呼叫 PHP mail() 發送此範例展示了早期 PHP 發送複雜 MIME 郵件的典型做法,理解其原理有助於除錯與維護舊系統,但新專案強烈建議採用成熟函式庫,避免重複造輪子並獲得持續的安全更新。