萬盛學電腦網

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

CodeIgniter 發送帶附件郵件完整實作指南

前言

CodeIgniter 內建 Email 類庫提供簡潔的郵件發送介面,支援多協議、附件、HTML/純文本、抄送/密送等功能。本文詳細說明如何發送帶附件的郵件,包含配置、多附件、內嵌圖片、錯誤處理與效能優化。

基礎配置 application/config/email.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$config['protocol']    = 'smtp';        // mail, sendmail, smtp
$config['smtp_host']   = 'ssl://smtp.gmail.com'; // 或 smtp.qq.com, smtp.163.com 等
$config['smtp_port']   = 465;           // SSL 465, TLS 587
$config['smtp_user']   = 'your@email.com';
$config['smtp_pass']   = 'your_app_password'; // 應用專用密碼,非登錄密碼
$config['smtp_timeout'] = 30;
$config['smtp_keepalive'] = true;       // 長連接複用

$config['charset']     = 'utf-8';
$config['wordwrap']    = true;
$config['wrapchars']   = 76;
$config['mailtype']    = 'html';        // html 或 text
$config['validation']  = true;          // 驗證郵箱格式
$config['priority']    = 3;             // 1=高 3=正常 5=低
$config['crlf']        = "\r\n";
$config['newline']     = "\r\n";
$config['bcc_batch_mode'] = false;
$config['bcc_batch_size'] = 200;
?>

控制器實作 application/controllers/Email_sender.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Email_sender extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('email');
        $this->load->helper('file'); // 用於 read_file
    }

    /**
     * 發送帶附件郵件
     */
    public function sendWithAttachment() {
        // 1. 基本設置
        $this->email->from('noreply@example.com', '系統通知');
        $this->email->to('user@example.com');
        $this->email->cc('cc@example.com');
        $this->email->bcc('bcc@example.com');
        
        $this->email->subject('您的報表附件 - ' . date('Y-m-d'));
        
        // 2. HTML 內容(支援內嵌圖片 CID)
        $message = $this->load->view('emails/report_template', [
            'username' => '張三',
            'report_date' => date('Y-m-d'),
            'cid_logo' => 'logo_cid', // 對應附件 CID
        ], true); // 第三參數 true 返回字串不輸出
        $this->email->message($message);
        
        // 3. 替代純文本內容(針對不支援 HTML 的客戶端)
        $this->email->set_alt_message("親愛的用戶,請查收附件報表。\n系統自動發送,請勿回覆。");

        // 4. 添加附件(支援多個)
        $attachments = [
            FCPATH . 'uploads/reports/monthly_report_202401.pdf',
            FCPATH . 'uploads/reports/data_export_202401.xlsx',
        ];
        foreach ($attachments as $file) {
            if (file_exists($file)) {
                $this->email->attach($file);
            } else {
                log_message('warning', "郵件附件不存在: {$file}");
            }
        }

        // 5. 內嵌圖片(HTML 中用  引用)
        $logoPath = FCPATH . 'assets/images/logo.png';
        if (file_exists($logoPath)) {
            $this->email->attach($logoPath, 'inline', 'logo_cid', 'logo.png');
        }

        // 6. 發送並處理結果
        if ($this->email->send()) {
            // 成功
            $this->session->set_flashdata('success', '郵件發送成功!');
            log_message('info', "郵件發送成功至: " . $this->email->to);
        } else {
            // 失敗:獲取詳細錯誤
            $error = $this->email->print_debugger(['headers', 'subject', 'body']);
            log_message('error', "郵件發送失敗: {$error}");
            $this->session->set_flashdata('error', '郵件發送失敗,請聯繫管理員');
        }
        
        redirect('dashboard');
    }

    /**
     * 批量發送(使用 BCC 保護收件人隱私)
     */
    public function sendBulk() {
        $recipients = ['a@ex.com', 'b@ex.com', 'c@ex.com', /* ... 1000+ */];
        
        $this->email->from('newsletter@example.com', '週報');
        $this->email->subject('每週技術分享 - ' . date('Y-m-d'));
        $this->email->message($this->load->view('emails/weekly', [], true));
        
        // 使用 BCC 批次模式(需配置 bcc_batch_mode=true)
        $this->email->bcc($recipients);
        
        if ($this->email->send()) {
            echo "批量發送已排隊";
        } else {
            echo "發送失敗: " . $this->email->print_debugger();
        }
    }
}
?>

視圖模板 application/views/emails/report_template.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <style>
        body {font-family: 'Microsoft JhengHei', sans-serif; line-height: 1.6; color: #333;}
        .container {max-width: 600px; margin: 0 auto; padding: 20px;}
        .header {text-align: center; border-bottom: 2px solid #007bff; padding-bottom: 10px;}
        .content {padding: 20px 0;}
        .footer {font-size: 0.85rem; color: #666; text-align: center; border-top: 1px solid #eee; padding-top: 10px;}
        .btn {display: inline-block; padding: 10px 20px; background: #007bff; color: white; text-decoration: none; border-radius: 4px;}
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <img src="cid:logo_cid" alt="Logo" style="max-height: 60px;">
        </div>
        <div class="content">
            <h2>親愛的 <?= $username ?>,您好</h2>
            <p>附件為 <?= $report_date ?> 的月度報表,請查收。</p>
            <p><a href="https://example.com/reports" class="btn">查看線上報表</a></p>
        </div>
        <div class="footer">
            <p>此郵件由系統自動發送,請勿直接回覆。</p>
            <p>© <?= date('Y') ?> Example Inc. All rights reserved.</p>
        </div>
    </div>
</body>
</html>

attach() 方法完整簽名

attach(string $path, string $disposition = 'attachment', string $name = null, string $mime = null): bool
參數說明預設
$path文件絕對路徑必填
$dispositionattachment (附件) 或 inline (內嵌圖片)attachment
$name顯示給收件人的文件名 / CID 標識符basename($path)
$mimeMIME 類型,null 自動檢測null

常見問題與解決方案

問題原因解決
附件收到是空文件/損壞路徑錯誤、文件讀取權限、輸出緩衝區汙染使用絕對路徑 FCPATH;檢查文件權限;確保無輸出前空白/echo;ob_start() 包裹
中文附件名亂碼RFC 2231 編碼問題CI 3.1.10+ 自動處理;舊版需手動 `= ?UTF-8?B?` 編碼或升級 CI
大附件發送超時/失敗SMTP 伺服器限制、PHP max_execution_time、memory_limit調大 timeout;分片發送;使用雲郵件服務 (SendGrid, Mailgun, Amazon SES)
Gmail/Outlook 進垃圾箱缺少 SPF/DKIM/DMARC、內容觸發規則、IP 信譽配置域名 DNS 記錄;使用專業郵件服務商;優化內容、避免敏感詞
內嵌圖片不顯示CID 不匹配、圖片路徑錯、郵件客戶端阻擋外部資源確保 attach(..., 'inline', 'cid_name') 與 HTML `cid:cid_name` 完全一致

進階:整合專業郵件服務商 (推薦生產環境)

<?php
// 使用 SendGrid API 替代 SMTP,更高送達率、統計、模板
require 'vendor/autoload.php'; // composer require sendgrid/sendgrid

function sendViaSendGrid(array $params): bool {
    $sg = new \SendGrid(getenv('SENDGRID_API_KEY'));
    $email = new \SendGrid\Mail\Mail();
    $email->setFrom($params['from_email'], $params['from_name']);
    $email->setSubject($params['subject']);
    $email->addTo($params['to_email'], $params['to_name'] ?? '');
    $email->addContent('text/html', $params['html']);
    $email->addContent('text/plain', $params['text'] ?? '');
    
    if (!empty($params['attachments'])) {
        foreach ($params['attachments'] as $att) {
            $attachment = new \SendGrid\Mail\Attachment();
            $attachment->setContent(base64_encode(file_get_contents($att['path'])));
            $attachment->setType($att['mime'] ?? 'application/octet-stream');
            $attachment->setFilename($att['name'] ?? basename($att['path']));
            $attachment->setDisposition($att['disposition'] ?? 'attachment');
            if (isset($att['cid'])) $attachment->setContentId($att['cid']);
            $email->addAttachment($attachment);
        }
    }
    
    try {
        $response = $sg->send($email);
        return $response->statusCode() >= 200 && $response->statusCode() < 300;
    } catch (Exception $e) {
        log_message('error', 'SendGrid 發送失敗: ' . $e->getMessage());
        return false;
    }
}
?>

總結

CodeIgniter Email 類庫功能完善,attach() 方法支援附件與內嵌圖片雙模式。生產環境建議:配置專業 SMTP/服務商、啟用 BCC 批次模式發送大量郵件、完善錯誤日誌與監控、設置 SPF/DKIM/DMARC 提升送達率。對於複雜郵件模板、營銷自動化、高併發發送需求,建議直接對接 SendGrid、Mailgun、Amazon SES 等專業 API 服務,將發送邏輯從應用層剝離。

copyright © 萬盛學電腦網 all rights reserved