如果 PHPMailer 失败,回退到本机 PHP 邮件功能

If PHPMailer fails, fallback to native PHP mail function

PHPMailer documentation 在其各种用例示例中建议代码的最后部分——发送——如果失败则应显示错误消息:

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

在失败的情况下,我更愿意做的是提供对本机 PHP mail() 函数的回退。好处是邮件还是会发给我,而且可以提示PHPMailer failed.

// 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';
}