專案常需發送郵件通知(註冊驗證、密碼重設、訂單通知等)。本文封裝一個 ThinkPHP 專用郵件發送函式 think_send_mail(),整合 PHPMailer,支援 SMTP 驗證、SSL 加密、附件發送、HTML 郵件等功能。
/**
* 系統郵件發送函式
* @param string $to 收件人信箱
* @param string $name 收件人名稱
* @param string $subject 郵件主旨
* @param string $body 郵件內容(支援 HTML)
* @param array $attachment 附件路徑陣列
* @return boolean|string 成功回傳 true,失敗回傳錯誤訊息
*/
function think_send_mail($to, $name, $subject = '', $body = '', $attachment = null) {
$config = C('THINK_EMAIL');
// 載入 PHPMailer 類別
vendor('PHPMailer.class#phpmailer');
$mail = new PHPMailer();
// 基本設定
$mail->CharSet = 'UTF-8';
$mail->IsSMTP();
$mail->SMTPDebug = 0; // 關閉除錯
$mail->SMTPAuth = true; // 啟用 SMTP 驗證
$mail->SMTPSecure = 'ssl'; // SSL 加密
$mail->Host = $config['SMTP_HOST'];
$mail->Port = $config['SMTP_PORT'];
$mail->Username = $config['SMTP_USER'];
$mail->Password = $config['SMTP_PASS'];
// 寄件人與回覆設定
$mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']);
$replyEmail = $config['REPLY_EMAIL'] ? $config['REPLY_EMAIL'] : $config['FROM_EMAIL'];
$replyName = $config['REPLY_NAME'] ? $config['REPLY_NAME'] : $config['FROM_NAME'];
$mail->AddReplyTo($replyEmail, $replyName);
// 郵件內容
$mail->Subject = $subject;
$mail->MsgHTML($body);
$mail->AddAddress($to, $name);
// 處理附件
if (is_array($attachment)) {
foreach ($attachment as $file) {
is_file($file) && $mail->AddAttachment($file);
}
}
return $mail->Send() ? true : $mail->ErrorInfo;
}
請將 PHPMailer 核心檔案放置於:
ThinkPHP/Extend/Vendor/PHPMailer/class.phpmailer.php
下載位址:PHPMailer 官方倉庫
'THINK_EMAIL' => array(
'SMTP_HOST' => 'smtp.example.com', // SMTP 伺服器
'SMTP_PORT' => '465', // SSL 埠號
'SMTP_USER' => 'mail@example.com', // 登入帳號
'SMTP_PASS' => 'your_password', // 登入密碼
'FROM_EMAIL' => 'mail@example.com', // 寄件人信箱
'FROM_NAME' => 'ThinkPHP', // 寄件人名稱
'REPLY_EMAIL' => '', // 回覆信箱(選填)
'REPLY_NAME' => '', // 回覆名稱(選填)
),
// 簡單文字郵件
think_send_mail('user@example.com', '張三', '歡迎註冊', '感謝您的註冊!');
// HTML 郵件 + 附件
$html = '<h1>訂單確認</h1><p>您的訂單編號:20240101001</p>';
$files = array('/path/to/invoice.pdf', '/path/to/contract.docx');
think_send_mail('user@example.com', '李四', '訂單確認通知', $html, $files);
原文出處:尛雷博客