要獲取郵件發送狀態,您可以使用PHP的mail()函數或者第三方庫如PHPMailer
mail()函數返回一個布爾值,表示郵件是否發送成功。如果發送失敗,它返回false;如果發送成功,它返回true。但是,這個函數不會提供詳細的錯誤信息。
示例代碼:
<?php
$to = "recipient@example.com";
$subject = "Test email";
$message = "This is a test email.";
$headers = "From: sender@example.com";
if (mail($to, $subject, $message, $headers)) {
echo "郵件發送成功";
} else {
echo "郵件發送失敗";
}
?>
PHPMailer是一個更強大的郵件發送庫,它提供了更多的功能和詳細的錯誤信息。要使用PHPMailer,首先需要下載并包含庫文件,然后設置郵件發送參數,最后調用send()方法。
示例代碼:
<?php
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
// 郵件服務器設置
$mail->SMTPDebug = 2; // 開啟詳細調試輸出
$mail->isSMTP(); // 設置郵件發送使用SMTP
$mail->Host = 'smtp.example.com'; // 設置郵件服務器地址
$mail->SMTPAuth = true; // 開啟使用SMTP認證功能
$mail->Username = 'sender@example.com'; // 設置發送郵件的用戶名
$mail->Password = 'your_password'; // 設置發送郵件的密碼
$mail->SMTPSecure = 'tls'; // 設置加密類型
$mail->Port = 587; // 設置SMTP連接端口
// 發件人和收件人
$mail->setFrom('sender@example.com', 'Sender Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
// 郵件內容設置
$mail->isHTML(true); // 設置郵件正文格式為HTML
$mail->Subject = 'Test email';
$mail->Body = 'This is a test email.';
// 發送郵件
$mail->send();
echo "郵件發送成功";
} catch (Exception $e) {
echo "郵件發送失敗: {$mail->ErrorInfo}";
}
?>
請注意,您需要根據實際情況修改示例代碼中的服務器地址、端口、用戶名、密碼等信息。