CodeIgniter 內建 Email 類別支援多種協定,本文說明如何使用 SMTP 發送 HTML 格式郵件,並解決常見的雙引號跳脫、除錯模式等問題。
application/config/email.php<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'smtp.126.com'; // SMTP 伺服器
$config['smtp_user'] = 'your_email@126.com'; // 寄件帳號
$config['smtp_pass'] = 'your_password'; // 密碼或授權碼
$config['smtp_port'] = 25; // 或 465 (SSL), 587 (TLS)
$config['charset'] = 'utf-8';
$config['wordwrap'] = TRUE;
$config['mailtype'] = 'html'; // 關鍵:發送 HTML 郵件
$config['newline'] = "\r\n"; // 部分 SMTP 要求 CRLF
$config['crlf'] = "\r\n";
public function send_html_mail() {
$this->load->library('email');
// 可選:覆蓋設定
$this->email->initialize([
'mailtype' => 'html',
'charset' => 'utf-8'
]);
$this->email->from('your_email@126.com', '系統名稱');
$this->email->to('recipient@example.com');
$this->email->subject('HTML 郵件測試');
$html_content = '
歡迎使用我們的服務
這是一封 HTML 格式 的測試郵件。
點擊連結
';
// 重要:移除 HTML 屬性中的雙引號,避免 CI 內部處理錯誤
$html_content = str_replace('"', '', $html_content);
$this->email->message($html_content);
// 開發階段建議開啟除錯
$this->email->print_debugger(['headers', 'subject', 'body']);
if ($this->email->send()) {
echo '發送成功';
} else {
show_error($this->email->print_debugger());
}
}
| 問題 | 原因 | 解決 |
|---|---|---|
| HTML 樣式失效 / 版面跑版 | CI 的 _prepare_body 會過濾雙引號 | 發送前 str_replace('"', '', $html) 或使用單引號包裹屬性 |
| 發送失敗 / 進入垃圾信箱 | 頻繁使用免費信箱(126/163/Gmail)大量發送 | 使用企業郵箱、設定 SPF/DKIM/DMARC、控制發送頻率 |
| SSL/TLS 連線失敗 | Port 465 需 SSL,Port 587 需 TLS | 設定 smtp_crypto = 'ssl' 或 'tls',並確認 PHP 開啟 openssl 擴充 |
print_debugger,避免洩露帳號密碼。