我有一个简单的HTML联系人表单,该表单使用服务器端PHP文件使用PHPMailer代码发送邮件。一切工作都非常顺利,我能够确认所有成功的邮件传输。
我的问题是我只能捕获并重定向成功邮件传输消息,而不能捕获并重定向失败消息。我所做的是我使用PHPMailer建议的“ try and catch”方法捕获错误,然后使用条件if语句测试$ mail-> send()值的真与假,以确定邮件是否已成功发送并定向该页面对应于我的错误页面或成功页面。
应该注意,如果用户在客户端禁用JavaScript,我将以非ajax备份方法对其进行测试。 Ajax方法工作正常。
我试图通过不通过互联网连接发送表单或禁用PHP文件中的某些代码(例如“ $ mail-> Port”或“ $ mail-> Host”,甚至网关密码)来模拟邮件发送失败。我的条件语句始终呈现“ false”值,导致显示成功消息。
以下是我的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;
答案 0 :(得分:0)
您发送了两次消息,第二次是在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");
};