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

CodeIgniter 發送郵件與除錯資訊列印:Email Library 完整設定

     編輯:PHP 綜合知識

基本發送流程

<?php
public function sendMail() {
    $this->load->library('email');
    
    // 設定發件人
    $this->email->from('noreply@example.com', '系統通知');
    
    // 設定收件人
    $this->email->to('user@example.com');
    
    // 可選:副本、密件副本
    $this->email->cc('manager@example.com');
    $this->email->bcc('admin@example.com');
    
    // 主旨與內容
    $this->email->subject('測試郵件主旨');
    $this->email->message('這是測試郵件內容,支援 HTML。');
    
    // 發送
    if ($this->email->send()) {
        echo '發送成功';
    } else {
        // 列印除錯資訊
        echo $this->email->print_debugger(['headers', 'subject', 'body']);
    }
}
?>

完整設定陣列(config/email.php)

<?php
$config['protocol'] = 'smtp';        // mail, sendmail, smtp
$config['smtp_host'] = 'ssl://smtp.gmail.com';
$config['smtp_port'] = 465;
$config['smtp_user'] = 'your@gmail.com';
$config['smtp_pass'] = 'app_password'; // 應用程式密碼
$config['smtp_timeout'] = 30;
$config['smtp_keepalive'] = true;

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

// 載入設定
$this->email->initialize($config);
?>

HTML 郵件與附件

$this->email->subject('HTML 郵件測試');
$this->email->message('
    <h1>標題</h1>
    <p>支援 <strong>HTML</strong> 內容</p>
    <img src="<?= base_url('assets/logo.png') ?>" alt="Logo">
');

// 附件
$this->email->attach('/path/to/file.pdf');
$this->email->attach('/path/to/image.jpg', 'attachment', 'photo.jpg', 'image/jpeg');

除錯資訊解讀

print_debugger() 回傳包含:

  • Headers:完整 SMTP 交握標頭
  • Subject:主旨編碼後內容
  • Body:郵件本文(含邊界標記)
  • Debug:SMTP 指令與回應碼(220, 250, 354, 221 等)

常見錯誤與解決

錯誤原因解決
Connection timed outPort 阻擋、防火牆檢查 465/587/25 埠、改用 SSL/TLS
Authentication failed帳密錯誤、未開啟 SMTPGmail 需開啟「較不安全的應用程式」或用應用程式密碼
550 Relay not permitted發件域未驗證、SPF/DKIM 缺失設定 DNS SPF/DKIM/DMARC、使用郵件服務商
Message rejected內容觸發垃圾郵件過濾避免可疑關鍵字、平衡圖文比例、加入退訂連結
SSL certificate problem憑證驗證失敗本機開發可暫時關閉驗證($config['smtp_crypto'] = 'ssl';)

批次發送優化

// 保持 SMTP 連線(需 smtp_keepalive = true)
$this->email->initialize(['smtp_keepalive' => true]);

foreach ($users as $user) {
    $this->email->clear(TRUE); // 清除收件人、主旨、內容,保留設定
    $this->email->to($user->email);
    $this->email->subject("親愛的 {$user->name},專屬優惠");
    $this->email->message(view('email/promo', ['user' => $user], true));
    $this->email->send();
}

// 發送完畢關閉連線
$this->email->close();

結語

CodeIgniter Email Library 封裝完整,支援多種協定、HTML、附件、批次發送。關鍵在於正確設定 SMTP 認證與 DNS 記錄,善用 print_debugger() 排查發送失敗原因。生產環境建議改用專業郵件服務(SendGrid、Mailgun、Amazon SES)提升送達率。

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