首页 > 解决方案 > 使用 phpmailer 时捕获和显示错误的问题

问题描述

我有一个简单的 HTML 联系表单,它使用服务器端 PHP 文件使用 PHPMailer 代码发送邮件。一切都很顺利,我能够确认所有成功的邮件传输。

我遇到的问题是我只能捕获和重定向成功邮件传输消息,但不能捕获和重定向失败消息。我所做的是我使用 PHPMailer 推荐的“try and catch”方法来捕获错误,然后使用条件 if 语句来测试 $mail->send() 值的真假,以确定邮件是否发送成功并定向该页面对应于我的错误或成功页面。

应该注意的是,我正在将此作为非 ajax 备份方法进行测试,以防用户在客户端禁用 JavaScript。ajax 方法工作正常。

我试图通过在没有 Internet 连接的情况下发送表单或禁用 PHP 文件中的某些代码(例如“$mail->Port”或“$mail->Host”,甚至网关密码)来模拟邮件发送失败。条件语句我总是呈现一个“假”值,导致显示成功消息。

以下是我的 PHP 代码的相关部分:

/* Create a new PHPMailer object. Passing TRUE to the constructor enables exceptions. */
$mail = new phpmailer( TRUE );
//
/* Open the try/catch block. */
try {
//
/* Set the mail sender. */
$mail->setFrom( 'mail-sender@gmail.com', 'mail-sender name' );
//
/* Add a recipient. */
//set who is recieving mail
$mail->addAddress( 'receipient@hotmail.com' );
//
/* Set the subject. */
$mail->Subject = 'New Order Request Message';
//
/* Set email to be sent as HTML */
$mail->isHTML( true );
//
/* Set the mail message body. */
$mail->Body = "<h3>New Order Request Message.</h3>
<style>
table, {
border: 1px solid black;
background-color: #f8f9f9 ;
}
}
td {
padding: 5px;
}
</style>
<div>
//
<table>
<tr>
<td>First Name: </td>
<td>$firstName</td> 
</tr>
<tr>
<td>Last Name: </td>
<td>$lastName</td> 
</tr>
<tr>
<td>Email: </td>
<td>$email</td>
</tr>
<tr>
<td>Telephone: </td>
<td>$telephone</td>
</tr>
<tr>
<td>Message: </td>
<td>$message: </td> 
</tr>
</table>
//
</div>";
//
/* SMTP parameters. */
/* Tells PHPMailer to use SMTP. */
$mail->isSMTP();
//
/* SMTP server address. */
$mail->Host = "smtp.gmail.com";
//
/* Use SMTP authentication. */
$mail->SMTPAuth = TRUE;
//
/* Set the encryption system. */
$mail->SMTPSecure = 'ssl';
//
//set who is sending mail
$mail->setFrom( 'myaccount@hotmail.com', 'My Name' );
//
//set login details for gmail account
$mail->Username = 'login-name@gmail.com';
$mail->Password = 'loing-password';
//
/* Set the SMTP port. */
$mail->Port = 465;
//      
/* Finally send the mail. */
$mail->send();
} catch (phpmailerException $e) {
} catch ( Exception $e ) {
} catch ( \Exception $e ) {
}
//
if(!$mail->send()) {
$mail_failure = "Something wrong happened. Mail was not sent."; 
$_SESSION["mail-failure"] = $mail_failure;
header("Location: form-errors.php");
} else {
$mail_success = "Mail sent successfully. Thank you.";   
$_SESSION["mail-success"] = $mail_success;
header("Location: form-success.php");
};
exit;

标签: phpemailphpmailer

解决方案


你发送了两次消息,第二次是在 try 块之外,所以那里发生的任何错误都不会被捕获。您还捕获了不存在的异常。像这样做:

   $mail->send();
} catch ( Exception | \Exception $e ) {
    $_SESSION["mail-failure"] = "Something went wrong. Mail was not sent: " . $e->getMessage();
    header("Location: form-errors.php");
    exit;
}
$_SESSION["mail-success"] = "Mail sent successfully. Thank you.";
header("Location: form-success.php");
};

推荐阅读