我正在尝试将PHPMailer用于一个小项目,但我对使用该软件进行错误处理感到困惑.希望有人有经验.当我设置电子邮件时,我使用:
$result = $mail->Send();
if(!$result) {
// There was an error
// Do some error handling things here
} else {
echo "Email successful";
}
Run Code Online (Sandbox Code Playgroud)
哪个工作正常,或多或少.问题是当出现错误时,PHPMailer似乎也将错误消除了,所以如果出现问题,它只是将该信息直接发送到浏览器,基本上打破了我试图做的任何错误处理.
有没有办法让这些消息沉默?它没有抛出异常,只是打印出错误,在我的测试用例中是:
invalid address: @invalid@email You must provide at least one recipient email address.
Run Code Online (Sandbox Code Playgroud)
它意味着是一个错误,但它应该驻留在$ mail-> ErrorInfo; 没有被软件回应.
Phi*_*off 98
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!
}
Run Code Online (Sandbox Code Playgroud)
Pho*_*ixS 21
您可以通过该方法获得有关错误的更多信息$mail->ErrorInfo.例如:
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
Run Code Online (Sandbox Code Playgroud)
这是您需要激活的异常模型的替代方法new PHPMailer(true).但如果可以使用异常模型,请将其用作@Phil Rykoff答案.
这来自github上的PHPMailer主页https://github.com/PHPMailer/PHPMailer.
Sim*_*rts 16
只是不得不自己解决这个问题.以上答案似乎没有考虑到这个
$mail->SMTPDebug = 0;选项.首次提出问题时可能无法使用.
如果您从PHPMail站点获得了代码,则默认为
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
https://github.com/Synchro/PHPMailer/blob/master/examples/test_smtp_gmail_advanced.php
将值设置为0以抑制错误并编辑代码的"catch"部分,如上所述.
Phi*_*Dev 16
请注意!!!在实例化PHPMailer时必须使用以下格式!
$mail = new PHPMailer(true);
Run Code Online (Sandbox Code Playgroud)
如果不这样做,则会忽略异常,并且您唯一能得到的就是来自例程的回声!我知道这是在创建之后很好但希望它会帮助某人.
小智 5
我们编写了一个包装类来捕获缓冲区并将打印输出转换为异常。这让我们可以升级 phpmailer 文件,而不必记住每次升级时都注释掉 echo 语句。
包装器类具有以下方法:
public function AddAddress($email, $name = null) {
ob_start();
parent::AddAddress($email, $name);
$error = ob_get_contents();
ob_end_clean();
if( !empty($error) ) {
throw new Exception($error);
}
}
Run Code Online (Sandbox Code Playgroud)