控制器中直接配置發送
public function send_mail() {
$this->load->library('email');
$config = [
'protocol' => 'smtp',
'smtp_host' => 'smtp.163.com',
'smtp_user' => 'your@163.com',
'smtp_pass' => 'your_password',
'smtp_port' => 25,
'mailtype' => 'html',
'charset' => 'utf-8',
'validate' => true,
'priority' => 1,
'crlf' => "\r\n",
'wordwrap' => true,
];
$this->email->initialize($config);
$this->email->from('your@163.com', '幫客之家');
$this->email->to('target@qq.com');
$this->email->subject('測試郵件');
$this->email->message('哈哈,測試郵件發送
');
$this->email->send();
echo $this->email->print_debugger(); // 調試輸出
}
配置文件複用(推薦)
- 創建
application/config/email.php
- 返回
$config 數組(同上)
- 控制器僅需
$this->load->library('email'); 自動載入配置,無需 initialize()
常見問題排查
- SMTP 驗證失敗:檢查郵箱是否開啟 SMTP 服務、授權碼是否正確
- 端口不通:嘗試 465 (SSL) 或 587 (TLS),對應設
smtp_crypto
- 中文亂碼:確保
charset=utf-8 且文件編碼為 UTF-8 無 BOM
- 發送慢:異步隊列處理,避免阻塞響應