<?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']);
}
}
?>
<?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); ?>
$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() 回傳包含:
| 錯誤 | 原因 | 解決 |
|---|---|---|
| Connection timed out | Port 阻擋、防火牆 | 檢查 465/587/25 埠、改用 SSL/TLS |
| Authentication failed | 帳密錯誤、未開啟 SMTP | Gmail 需開啟「較不安全的應用程式」或用應用程式密碼 |
| 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)提升送達率。