[英]If PHPMailer fails, fallback to native PHP mail function
PHPMailer文檔在其各種用例示例中表明代碼的最后部分 - 發送 - 如果失敗則應顯示錯誤消息:
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
在發生故障時我更願意做的是提供本機PHP mail()函數的回退。 好處是電子郵件仍會發送給我,它可以發出PHPMailer失敗的通知。
// If PHPMailer code library fails (for whatever reason), fallback to mail()
if (!mail->send()) {
// just an example
$to = 'me@mydomain.com';
$subject = 'You have a new e-mail subscriber + ERROR REPORT';
$message = 'user input data and error description here';
mail($to, $subject, $message);
} else {
// other settings defined earlier in script
$mail->Subject = 'You have a new e-mail subscriber';
$mail->Body = $message;
$mail->send();
}
我對使用PHPMailer語言作為IF
表達式猶豫不決,因為PHP的完全回退對我來說似乎更安全可靠。 有沒有更好的方法來寫這個?
編輯:基於下面的評論,這里有一點澄清。 PHPMailer默認使用mail()
。 因此,此問題不適用於默認方案。 但是,我的實現始終使用需要用戶名和密碼的自定義SMTP設置(例如smtp.google.com)。 我的問題涉及自定義郵件服務器出現問題的可能性,用戶名或密碼。 因此,我正在尋找一個超越屏幕上簡單錯誤消息的后備解決方案。
您應該首先為PHPMailer進行分配。 在if語句中, !$mail->send()
部分已經嘗試發送郵件。 所以在你的else
語句中,實際上你用PHPMailer再次發送郵件。 你可以使用如下。 它將嘗試使用PHPMailer發送郵件,如果失敗,它將使用PHP的郵件功能。
$mail->Subject = 'You have a new e-mail subscriber';
$mail->Body = $message;
if (!$mail->send()) {
$to = 'me@mydomain.com';
$subject = 'You have a new e-mail subscriber + ERROR REPORT';
$message = 'user input data and error description here';
mail($to, $subject, $message);
}
繼我的評論之后,以下是如何使用SMTP傳輸回退到使用PHPMailer中的mail()
傳輸:
...
$mail->isSMTP();
if (!$mail->send()) {
//Fall back to using mail()
$mail->isMail();
if (!$mail->send()) {
echo 'Message failed to send';
} else {
echo 'Message sent via mail()';
}
} else {
echo 'Message sent via SMTP';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.