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

ECMall 整合 PHPMailer 實現 SMTP SSL/TLS 加密郵件發送完整教學

     編輯:PHP 綜合知識

問題背景

ECMall 內建的 PHPMailer 版本過舊,不支援 SMTPSecure(SSL/TLS),導致無法連接要求加密的郵件伺服器(如 Gmail、QQ 企業郵箱、Outlook 等)。

解決步驟總覽

  1. 替換 lib/phpmailer/ 為新版 PHPMailer(支援 SSL/TLS)。
  2. 修改兩個核心 Library:mail.lib.php、mail_queue.lib.php,傳遞 $SMTPSecure 參數。
  3. 封裝函數 get_mailer() 讀取後台設定並實例化。
  4. 後台設定頁新增「郵件伺服器加密方式」選項(無/SSL/TLS)。
  5. 修改測試郵件 AJAX 傳遞新參數。

詳細修改點

1. 覆蓋 PHPMailer

下載新版 PHPMailer,覆蓋 core/lib/phpmailer/ 目錄。

2. 修改 mail.lib.php / mail_queue.lib.php

// 建構子新增 $SMTPSecure 參數
function __construct($from, $email, $protocol, $host='', $port='', $user='', $pass='', $SMTPSecure=false) {
    $this->Mailer($from, $email, $protocol, $host, $port, $user, $pass, $SMTPSecure);
}

function Mailer($from, $email, $protocol, $host='', $port='', $user='', $pass='', $SMTPSecure=false) {
    // ... 內部實例化 PHPMailer
    $this->mailer->SMTPSecure = $SMTPSecure; // 'ssl' 或 'tls'
    // ...
}

3. 修改 global.lib.php 中的 get_mailer()

$secure = Conf::get('email_ssl'); // 讀取後台設定
$mailer = new Mailer($sender, $from, $protocol, $host, $port, $username, $password, $secure);

4. 後台模板 setting.email_setting.html 新增選項

<tr>
  <th>郵件伺服器加密方式:</th>
  <td>
    {html_radios name="email_ssl" options=$email_ssl checked=$setting.email_ssl}
    <label class="field_notice">需 PHP 支援 OpenSSL 擴展</label>
  </td>
</tr>

5. 後台控制器 setting.app.php

// email_setting() 方法中
$this->assign('email_ssl', [
    0 => Lang::get('no'),
    1 => 'SSL',
    2 => 'TLS',
]);

// 儲存時
$data['email_ssl'] = $_POST['email_ssl'];

// send_test_email() 方法中
$email_ssl = $_POST['email_ssl'];
$mailer = new Mailer($email_from, $email_addr, $email_type, $email_host, $email_port, $email_id, $email_pass, $email_ssl);

6. 前端 AJAX 傳遞 email_ssl

var email_ssl = $('input[name="email_ssl"]:checked').val();
data: '...&email_ssl=' + email_ssl

驗證與注意事項

  • PHP 必須編譯 --with-openssl 或載入 openssl 擴展(php -m | grep openssl)。
  • SSL 通常用 465 埠,TLS 用 587 埠(視郵件商而定)。
  • 自簽憑證或測試環境可能需設定 $mailer->SMTPAutoTLS = false; 或 SMTPOptions 忽略驗證(僅測試用)。
  • TLS 模式未實測,建議優先使用 SSL。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved