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

CodeIgniter 透過 SMTP 發送 HTML 郵件完整設定指南

     編輯:PHP 相關知識

CodeIgniter 透過 SMTP 發送 HTML 郵件完整設定指南

CodeIgniter 內建 Email 類別支援多種協定,本文說明如何使用 SMTP 發送 HTML 格式郵件,並解決常見的雙引號跳脫、除錯模式等問題。

1. 設定檔 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";

2. 控制器發送範例

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,避免洩露帳號密碼。
  • 大量發送請使用隊列(如 Redis + Worker)非同步處理,避免阻塞請求。
  • 郵件內容盡量使用內聯 CSS,相容性最佳。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved