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