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

PHPMailer 透過 126.com SMTP 發送郵件完整範例

     編輯:PHP 綜合知識

以下示範使用 PHPMailer 透過 126.com SMTP 伺服器發送 HTML 郵件,包含 SSL/TLS 設定、認證與錯誤處理。

<?php
require_once '../class.phpmailer.php';

$mail = new PHPMailer();
$mail->CharSet = 'utf-8';

// SMTP 設定
$mail->isSMTP();
$mail->Host       = 'smtp.126.com';
$mail->SMTPAuth   = true;
$mail->Username   = 'your_account@126.com';
$mail->Password   = 'your_password';        // 使用客戶端授權碼
$mail->SMTPSecure = 'ssl';                  // 126 支援 SSL
$mail->Port       = 465;                    // SSL 埠號
$mail->SMTPDebug  = 0;                      // 除錯模式:0=關閉, 2=詳細

// 寄件人與收件人
$mail->setFrom('your_account@126.com', '發件人名稱');
$mail->addAddress('recipient@example.com', '收件人名稱');

// 郵件內容
$mail->isHTML(true);
$mail->Subject = '測試郵件主旨';
$mail->Body    = '我終於發送郵件成功了!<br><a href="https://example.com">連結</a>';
$mail->AltBody = '請使用支援 HTML 的郵件用戶端檢視。';

// 發送與錯誤處理
if (!$mail->send()) {
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message sent!';
}
?>

關鍵點說明

  • 授權碼 ≠ 登入密碼:126/163/QQ 等郵箱需在網頁版設定「客戶端授權碼」並啟用 SMTP 服務。
  • SMTPSecure = 'ssl' + Port = 465 是 126 推薦設定;若用 TLS 請改 Port = 587。
  • isHTML(true) 才會解析 Body 中的 HTML 標籤。
  • 建議保留 AltBody 給純文字郵件用戶端。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved