首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 發送帶附件郵件:原生 MIME 組裝與 PHPMailer 現代實踐對比

     編輯:PHP 綜合知識

方案一:原生 MIME 組裝 (教學用)

手動構建 multipart/mixed 郵件結構:

<?php
function sendMailWithAttachment($to, $subject, $body, $filePath, $fileName, $from = 'me@example.com') {
    $boundary = '==MULTIPART_BOUNDARY_' . md5(microtime()) . '==';
    $headers = "From: $from\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";

    $message = "--$boundary\r\n";
    $message .= "Content-Type: text/plain; charset=UTF-8\r\n";
    $message .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $message .= chunk_split(base64_encode($body)) . "\r\n";

    if (is_file($filePath)) {
        $content = chunk_split(base64_encode(file_get_contents($filePath)));
        $message .= "--$boundary\r\n";
        $message .= "Content-Type: application/octet-stream; name=\"$fileName\"\r\n";
        $message .= "Content-Transfer-Encoding: base64\r\n";
        $message .= "Content-Disposition: attachment; filename=\"$fileName\"\r\n\r\n";
        $message .= $content . "\r\n";
    }
    $message .= "--$boundary--\r\n";

    return mail($to, '=?UTF-8?B?' . base64_encode($subject) . '?=', $message, $headers);
}

方案二:PHPMailer (生產環境標準)

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

function sendMailModern($to, $subject, $body, $attachments = [], $from = 'me@example.com', $fromName = '') {
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host = 'smtp.example.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'user';
        $mail->Password = 'pass';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;

        $mail->setFrom($from, $fromName ?: $from);
        $mail->addAddress($to);
        $mail->Subject = $subject;
        $mail->msgHTML($body);
        $mail->AltBody = strip_tags($body);

        foreach ($attachments as $att) {
            // $att = ['path'=>'/tmp/a.pdf', 'name'=>'report.pdf']
            $mail->addAttachment($att['path'], $att['name']);
        }

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}

兩者對比

維度原生 mail() + MIMEPHPMailer (SMTP)
依賴零 (內建)Composer 套件
編碼處理手動 base64/quoted-printable自動
附件支援手動組裝 boundaryaddAttachment() 一行
HTML 郵件手動構建 multipart/alternativemsgHTML() 自動生成 text 版
SMTP 認證/加密不支援 (需本地 MTA)完整支援 TLS/SSL、OAuth2
錯誤處理/除錯極難詳細異常、SMTP 對話日誌
發送可靠性低 (依賴本地 sendmail/postfix)高 (直連 SMTP 服務商)
效能 (大量發送)差 (每封建立連線)支援 Keep-Alive、批次發送

生產環境必做清單

  1. 使用 **專業 SMTP 服務商** (SendGrid, Mailgun, Amazon SES, Postmark, 阿里雲郵件推送)。
  2. 配置 **SPF / DKIM / DMARC** DNS 記錄,建立域名信譽。
  3. **非同步發送**:寫入 Redis/RabbitMQ 隊列,Worker 消費發送,API 秒級回應。
  4. **模板引擎** (Blade/Twig/Plates) 分離內容與樣式,支援多語言。
  5. **退訂/退信處理**:監聽 Webhook,自動清理無效地址。
  6. **測試**:Mailtrap / Ethereal Email 捕獲測試郵件,驗證樣式與附件。

結語

原生 MIME 組裝適合理解郵件協議結構,但生產系統 **務必** 使用 PHPMailer/Symfony Mailer 等成熟庫搭配專業 SMTP 服務。非同步隊列、模板化、信譽管理是企業級郵件系統的標配三件套。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved