使用 PHPMailer 进行错误处理

2022-08-30 09:54:04

我正在尝试将PHPMailer用于一个小项目,但我对该软件的错误处理有点困惑。希望有人有这方面的经验。当我设置了电子邮件并使用:

$result = $mail->Send();

if(!$result) {
    // There was an error
    // Do some error handling things here
} else {
    echo "Email successful";
}

这或多或少工作正常。问题是当有错误时,PHPMailer似乎也会回显错误,所以如果有问题,它只是将该信息直接发送到浏览器,基本上会破坏我试图做的任何错误处理。

有没有办法让这些信息沉默?它没有抛出异常,它只是打印出错误,在我的测试用例中是:

invalid address: @invalid@email You must provide at least one recipient email address.

它意味着是一个错误,但它应该驻留在$mail->ErrorInfo;没有被软件回声。


答案 1

PHPMailer 使用 Exceptions。尝试采用以下代码

require_once '../class.phpmailer.php';

$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch

try {
  $mail->AddReplyTo('name@yourdomain.com', 'First Last');
  $mail->AddAddress('whoto@otherdomain.com', 'John Doe');
  $mail->SetFrom('name@yourdomain.com', 'First Last');
  $mail->AddReplyTo('name@yourdomain.com', 'First Last');
  $mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
  $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
  $mail->MsgHTML(file_get_contents('contents.html'));
  $mail->AddAttachment('images/phpmailer.gif');      // attachment
  $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
  $mail->Send();
  echo "Message Sent OK\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}

答案 2

您可以使用该方法获取有关错误的详细信息。例如:$mail->ErrorInfo

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

这是需要使用 激活的异常模型的替代方法。但如果可以使用异常模型,请将其用作Rykoff答案@Phil。new PHPMailer(true)

这来自github上PHPMailer的主页 https://github.com/PHPMailer/PHPMailer


推荐