发布日期:2018-03-26
如何处理PHPMailer中的报错信息?+ 查看更多
如何处理PHPMailer中的报错信息?
+ 查看更多
发布日期:2018-03-10 14:56
分类:PHP
浏览次数:614
如下:
我尝试在一个小项目中使用PHPMailer,但我对于这个软件的错误处理有点困惑。希望有人能够处理它。当我设置电脑邮件时我使用:
我尝试在一个小项目中使用PHPMailer,但我对于这个软件的错误处理有点困惑。希望有人能够处理它。当我设置电脑邮件时我使用:
$result = $mail->Send(); if(!$result) { // There was an error // Do some error handling things here} else { echo "Email successful";}
这段代码基本可以运行,但是当有一个错误时就出现了问题。PHPMailer也输出了错误信息,如果有错误的话,就会直接向浏览器发送信息,最终导致我不能按照想法处理错误信息。有什么方式让PHPMailer不输出信息吗?它不会抛出异常,只会打印出错误,
我遇到的错误是错误是这样的:
我遇到的错误是错误是这样的:
invalid address: @invalid@email You must provide at least one recipient email address.
像这样的错误信息应该保留在$mail->ErrorInfo中,而不是被这个软件输出。
回答:
简单的说,您可以在实例化PHPMailer的时候指定不输出错误:$mail = new PHPMailer(true) //true意味着不输出,而是抛异常
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!}