CodeIgniter 內建 Email 類庫支援 SMTP、SSL/TLS、HTML/純文本、附件、多收件者、BCC、自定義標頭、郵件隊列等功能。本文提供生產級配置範本、常見坑點排除與進階擴充建議。
$this->load->library('email');
$config = [
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com', // SSL 加密協定在 host 前綴
'smtp_port' => 465, // SSL 465 / TLS 587
'smtp_user' => 'your@gmail.com',
'smtp_pass' => 'app_specific_password', // 非登入密碼,需開啟 2FA 產生應用程式密碼
'smtp_timeout' => 30,
'smtp_crypto' => 'ssl', // 明確指定加密方式 (CI 3.1+)
'mailtype' => 'html',
'charset' => 'utf-8',
'newline' => "\r\n", // 關鍵:部分 SMTP 伺服器要求 CRLF
'crlf' => "\r\n",
'wordwrap' => TRUE,
'priority' => 3, // 1=高 3=正常 5=低
'validate' => TRUE, // 驗證 Email 格式
];
$this->email->initialize($config);
$this->email->from('your@gmail.com', '系統名稱');
$this->email->to('user@example.com');
$this->email->cc('cc@example.com');
$this->email->bcc('bcc@example.com');
$this->email->subject('測試郵件');
$this->email->message('HTML 內容
支援中文
');
$this->email->set_alt_message('純文本備用內容'); // 非 HTML 客戶端回退
if ($this->email->send()) {
echo '發送成功';
} else {
show_error($this->email->print_debugger()); // 除錯輸出完整 SMTP 交互
}
建立 application/config/email.php,內容為 $config 陣列,CI 會自動載入,無需 initialize()。
$this->email->attach('/path/to/report.pdf', 'application', 'report_2024.pdf', 'base64');
// 內嵌圖片 (HTML 中用
)
$this->email->attach('/path/to/logo.png', 'inline', 'logo');
foreach ($users as $user) {
$this->email->clear(TRUE); // TRUE = 清除附件/標頭
$this->email->to($user->email);
$this->email->subject("親愛的 {$user->name},專屬優惠");
$this->email->message($template);
$this->email->send();
}
// 寫入資料表/Redis 隊列
$queue = [
'to' => $email,
'subject' => $subject,
'message' => $message,
'headers' => $headers,
'attempts' => 0,
'created_at' => date('Y-m-d H:i:s'),
];
$this->db->insert('email_queue', $queue);
背景 Worker (CLI Script / Supervisor) 輪詢發送,失敗重試、記錄日誌。
| 提供商 | Host | Port | Crypto | 備註 |
|---|---|---|---|---|
| Gmail | ssl://smtp.gmail.com | 465 | ssl | 需應用程式密碼 |
| Outlook/Office365 | tls://smtp.office365.com | 587 | tls | STARTTLS |
| SendGrid | tls://smtp.sendgrid.net | 587 | tls | API Key 做密碼 |
| Mailgun | tls://smtp.mailgun.org | 587 | tls | API Key |
| 阿里雲企業郵箱 | ssl://smtp.qiye.aliyun.com | 465 | ssl | |
| 騰訊企業郵箱 | ssl://smtp.exmail.qq.com | 465 | ssl |
print_debugger() 觀察 SMTP 指令/回應碼 (220, 250, 535, 550...)。smtp_timeout 過短、DNS 解析失敗。charset=utf-8、檔案儲存為 UTF-8 無 BOM、mailtype=html 時 <meta charset="UTF-8">。若不想用 SMTP,可擴充 CI_Email 覆寫 _send(),改呼叫 SendGrid/Mailgun/Postmark HTTP API,享受更高到達率與統計分析。