以下示範使用 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!';
}
?>
SMTPSecure = 'ssl' + Port = 465 是 126 推薦設定;若用 TLS 請改 Port = 587。isHTML(true) 才會解析 Body 中的 HTML 標籤。AltBody 給純文字郵件用戶端。