萬盛學電腦網

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

PHP 發送帶附件電子郵件:原生 Mail 類別完整實作與 MIME 結構解析

PHP 內建 `mail()` 函式僅支援純文字郵件,發送附件需手動構建 MIME Multipart 訊息結構。本文提供完整的 `CMailFile` 類別實作,支援多附件、Base64 編碼、自定義 MIME 類型、檔名編碼,並解析 MIME 結構原理。

MIME Multipart 郵件結構

MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="==BOUNDARY=="

--==BOUNDARY==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit

純文字郵件內容

--==BOUNDARY==
Content-Type: application/pdf; name="report.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="report.pdf"

JVBERi0xLjQKJcfsj6... (Base64 編碼內容)

--==BOUNDARY==--

完整 CMailFile 類別實作

<?php
class CMailFile
{
    private string $subject;
    private string $to;
    private string $from;
    private string $bodyText;
    private array $attachments = [];
    private string $boundary;

    public function __construct(string $subject, string $to, string $from, string $bodyText)
    {
        $this->subject = $subject;
        $this->to = $to;
        $this->from = $from;
        $this->bodyText = $bodyText;
        $this->boundary = '==MULTIPART_' . md5(microtime() . random_bytes(16)) . '==';
    }

    public function addAttachment(string $filePath, string $fileName = '', string $mimeType = ''): self
    {
        if (!is_file($filePath) || !is_readable($filePath)) {
            throw new InvalidArgumentException("Attachment not found or not readable: $filePath");
        }

        $fileName = $fileName ?: basename($filePath);
        $mimeType = $mimeType ?: $this->guessMimeType($filePath);

        $this->attachments[] = [
            'path'     => $filePath,
            'name'     => $fileName,
            'mime'     => $mimeType,
            'content'  => $this->encodeFile($filePath),
        ];
        return $this;
    }

    public function send(): bool
    {
        $headers = $this->buildHeaders();
        $message = $this->buildMessage();

        // 使用 -f 參數設定 Envelope Sender (避免進垃圾郵件)
        $additionalParams = '-f' . $this->from;

        return mail($this->to, $this->subject, $message, $headers, $additionalParams);
    }

    private function buildHeaders(): string
    {
        $headers = [
            "From: {$this->from}",
            "Reply-To: {$this->from}",
            "X-Mailer: PHP/" . PHP_VERSION,
            "MIME-Version: 1.0",
            "Content-Type: multipart/mixed; boundary=\"{$this->boundary}\"",
        ];
        return implode("\r\n", $headers);
    }

    private function buildMessage(): string
    {
        $parts = [];

        // 文字內容部分
        $parts[] = "--{$this->boundary}";
        $parts[] = 'Content-Type: text/plain; charset="utf-8"';
        $parts[] = 'Content-Transfer-Encoding: 7bit';
        $parts[] = '';
        $parts[] = $this->bodyText;

        // 附件部分
        foreach ($this->attachments as $att) {
            $parts[] = "--{$this->boundary}";
            $parts[] = "Content-Type: {$att['mime']}; name=\"{$att['name']}\"";
            $parts[] = 'Content-Transfer-Encoding: base64';
            $parts[] = "Content-Disposition: attachment; filename=\"{$att['name']}\"";
            $parts[] = '';
            $parts[] = $att['content'];
        }

        // 結束邊界
        $parts[] = "--{$this->boundary}--";
        $parts[] = ''; // 結尾空行

        return implode("\r\n", $parts);
    }

    private function encodeFile(string $path): string
    {
        $content = file_get_contents($path);
        return chunk_split(base64_encode($content)); // RFC 2045: 每 76 字元換行
    }

    private function guessMimeType(string $path): string
    {
        $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
        $map = [
            'pdf' => 'application/pdf',
            'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg',
            'png' => 'image/png', 'gif' => 'image/gif',
            'doc' => 'application/msword',
            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'xls' => 'application/vnd.ms-excel',
            'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'zip' => 'application/zip', 'txt' => 'text/plain',
            'csv' => 'text/csv',
        ];
        return $map[$ext] ?? 'application/octet-stream';
    }
}

使用範例

<?php
require 'CMailFile.php';

$mail = new CMailFile(
    '月報表 - 2024年1月',
    'manager@example.com',
    'system@example.com',
    '您好,附件為本月業務報表,請查收。'
);

$mail->addAttachment('/reports/monthly_202401.pdf', 'monthly_report.pdf', 'application/pdf')
     ->addAttachment('/reports/data.xlsx', 'raw_data.xlsx');

if ($mail->send()) {
    echo '郵件發送成功';
} else {
    echo '郵件發送失敗,請檢查 mail log';
}
?>

進階:HTML 格式郵件 + 純文字替代 (multipart/alternative)

<?php
class CMailAdvanced extends CMailFile
{
    private string $bodyHtml = '';

    public function setHtmlBody(string $html): self
    {
        $this->bodyHtml = $html;
        return $this;
    }

    protected function buildMessage(): string
    {
        // 外層 mixed 包含 alternative + attachments
        $outerBoundary = $this->boundary;
        $innerBoundary = '==ALTERNATIVE_' . md5($outerBoundary) . '==';

        $parts = [];

        // 外層 multipart/mixed
        $parts[] = "--{$outerBoundary}";
        $parts[] = "Content-Type: multipart/alternative; boundary=\"{$innerBoundary}\"";
        $parts[] = '';

        // 內層 text/plain
        $parts[] = "--{$innerBoundary}";
        $parts[] = 'Content-Type: text/plain; charset="utf-8"';
        $parts[] = 'Content-Transfer-Encoding: 7bit';
        $parts[] = '';
        $parts[] = $this->bodyText;

        // 內層 text/html
        $parts[] = "--{$innerBoundary}";
        $parts[] = 'Content-Type: text/html; charset="utf-8"';
        $parts[] = 'Content-Transfer-Encoding: quoted-printable';
        $parts[] = '';
        $parts[] = $this->encodeQuotedPrintable($this->bodyHtml);

        $parts[] = "--{$innerBoundary}--";

        // 附件 (同父類別)
        foreach ($this->attachments as $att) {
            $parts[] = "--{$outerBoundary}";
            $parts[] = "Content-Type: {$att['mime']}; name=\"{$att['name']}\"";
            $parts[] = 'Content-Transfer-Encoding: base64';
            $parts[] = "Content-Disposition: attachment; filename=\"{$att['name']}\"";
            $parts[] = '';
            $parts[] = $att['content'];
        }

        $parts[] = "--{$outerBoundary}--";
        $parts[] = '';

        return implode("\r\n", $parts);
    }

    private function encodeQuotedPrintable(string $str): string
    {
        return imap_8bit($str); // 需啟用 imap 擴充,或自行實作
    }
}

常見問題與解決

問題原因解決
附件收到損壞/無法開啟Base64 編碼未分行 (超過 76 字元)、二進位檔案讀取模式錯誤使用 `chunk_split(base64_encode())`、確保 `file_get_contents` 二進位安全
中文檔名亂碼RFC 2231 編碼缺失檔名用 `=?UTF-8?B?` . base64_encode($name) . `?=` 格式
郵件進垃圾箱無 SPF/DKIM/DMARC、IP 信譽差、內容觸發規則設定 DNS 記錄、使用專業郵件服務 (SendGrid, Mailgun, AWS SES)
大附件發送失敗PHP `memory_limit`、`post_max_size`、MTA 限制分塊讀取編碼、調整限制、改用 SMTP 庫 (PHPMailer)

現代替代方案:PHPMailer / Symfony Mailer

生產環境強烈建議使用成熟庫:

<?php
// PHPMailer 範例
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

$mail = new PHPMailer(true);
$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@example.com', 'System');
$mail->addAddress('to@example.com');
$mail->Subject = 'Subject';
$mail->Body = 'HTML body';
$mail->AltBody = 'Plain text body';
$mail->addAttachment('/path/file.pdf');

$mail->send();
copyright © 萬盛學電腦網 all rights reserved