我正在尝试将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;中。不会被软件回显。
PHPMAiler使用异常。尝试采用以下代码:
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! }