早期 PHP mail() 或簡易 Socket 發信無需認證,但 263、163、新浪等主流免費郵件服務商陸續啟用 SMTP AUTH,導致舊程式失效。本文詳細說明 SMTP AUTH LOGIN 機制,並提供 send_mail 類別修改指南,實作基於 Base64 的挑戰-回應認證流程。
C: AUTH LOGIN S: 334 dXNlcm5hbWU6 (Base64 "username:") C: dXNlcm5hbWU6 (Base64 編碼的帳號) S: 334 cGFzc3dvcmQ6 (Base64 "password:") C: cGFzc3dvcmQ6 (Base64 編碼的密碼) S: 235 Authentication successful
$auth、$authuser、$authpasswd$auth 為真則發送 EHLO,否則維持 HELOAUTH LOGIN、Base64 帳號、Base64 密碼,各步驟檢查 334/235 回應碼do_command() 迴圈讀取直到回應碼後為空格(單行結束)<?php
include("sendmail.class.php3");
$sendmail = new send_mail("smtp.263.net", true, "username", "password", "hello", true);
$sendmail->send("to@email.com", "from@email.com", "測試", "This is a test!");
?>
此實作為早期 SMTP 認證過渡期產物,現代專案強烈建議使用支援 STARTTLS、OAuth2 的郵件函式庫。