php - PHP 邮件程序和 Ajax
问题描述
我正在使用 Mail PHP 发送邮件。我必须使用外部 SMTP,所以我添加了 PHP Mailer。
问题是成功的消息不会返回到表单中。
这是代码
$output = json_encode(array('type'=>'message', 'text' => 'Ciao '.$user_Name .', grazie per averci contattato.'));
die($output);
$mail->Send();
如果我先发送邮件,则邮件已发送,但未显示成功消息。
如果我把第一个 json_encode,消息显示但邮件不发送
我也试过这段代码
$output = json_encode(array('type'=>'message', 'text' => 'Ciao '.$user_Name .', grazie per averci contattato.'));
echo($output);
return;
但它不起作用。
更新
我又试了一次,但没有通过成功消息(虽然邮件正确到达)
如果有帮助,这是完整的代码
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
if($_POST)
{
$to_Email = "mail@mail.it"; //Replace with recipient email address
$subject = 'MB INOX Compilazione form online'; //Subject line for emails
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Phone = $_POST["userPhone"];
//$user_Subject = $_POST["userSubject"];
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_Name)<3) // If length is less than 3 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Il nome è troppo corto o vuoto!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Inserire un indirizzo email valido!'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Il messaggio è troppo corto o vuoto!'));
die($output);
}
$message_Body = "<strong>Nome: </strong>". $user_Name ."<br>";
$message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
//$message_Body .= "<strong>Phone: </strong>". $user_Phone ."<br>";
// $message_Body .= "<strong>Subject: </strong>". $user_Subject ."<br>";
$message_Body .= "<strong>Messaggio: </strong>". $user_Message ."<br>";
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
$mail->Host = "xxxxxxxxx"; // use $mail->Host = gethostbyname('smtp.gmail.com'); // if your network does not support SMTP over IPv6
$mail->Port = 587; // TLS only
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->SMTPAuth = true;
$mail->Username = 'xxxxx';
$mail->Password = 'xxxxxxxx';
$mail->setFrom('xxxxxxx', 'MB Inox');
$mail->addAddress($to_Email, 'MB Inox');
$mail->Subject = $subject;
$mail->msgHTML($message_Body); //$mail->msgHTML(file_get_contents('contents.html'), __DIR__); //Read an HTML message body from an external file, convert referenced images to embedded,
$mail->AltBody = 'HTML messaging not supported';
// $mail->addAttachment('images/phpmailer_mini.png'); //Attach an image file
if (!$mail->send()) {
echo 'Mail Not send';
} else {
$output = json_encode(array('type'=>'message', 'text' => 'Ciao '.$user_Name .', grazie per averci contattato.'));
echo($output);
}
}
?>
这是原始代码
<?php
if($_POST)
{
$to_Email = "mail@mail.it"; //Replace with recipient email address
$subject = 'MB INOX Compilazione form online'; //Subject line for emails
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Phone = $_POST["userPhone"];
//$user_Subject = $_POST["userSubject"];
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_Name)<3) // If length is less than 3 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Il nome è troppo corto o vuoto!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Inserire un indirizzo email valido!'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Il messaggio è troppo corto o vuoto!'));
die($output);
}
$message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
$message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
$message_Body .= "<strong>Phone: </strong>". $user_Phone ."<br>";
// $message_Body .= "<strong>Subject: </strong>". $user_Subject ."<br>";
$message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";
$headers = "From: " . strip_tags($user_Email) . "\r\n";
$headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
//proceed with PHP email.
/*$headers = 'From: '.$user_Email.'' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
*/
$sentMail = @mail($to_Email, $subject, $message_Body, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Errore. Messaggio non inviato'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Ciao '.$user_Name .', grazie per averci contattato.'));
die($output);
}
}
?>
解决方案
您可能希望在执行其他操作之前检查邮件是否已发送。因此,使用下面的代码,检查$mail->send()
此操作是否返回 true,这意味着它失败了,我们可以做其他事情。否则,我们可以继续处理我们的 json。
if (!$mail->send()) {
echo 'Mail Not send';
} else {
$output = json_encode(array('type'=>'message', 'text' => 'Ciao '.$user_Name .', grazie per averci contattato.'));
echo($output);
}
推荐阅读
- c# - ASP.NET MVC C# 应用程序中安全可靠的 HTTPCookie 存储
- braintree - 如何异步获取 Braintree 中的交易状态信息?
- pycharm - 无法在 pycharm 中使用 pipenv
- gdb - 如何安装 RISCV64 gdb?
- javascript - 如何在控制台中更新字符串而不是重复它
- javascript - Javascript (React) - 如何识别助手和实用程序,确保项目的正确可扩展性?
- mysql - 无法确定外键约束失败
- c++ - 使用 c++ stdlib 从管道非阻塞读取
- istio - 如何使用 istio-operator 更改 istiod 部署的配置?
- dialogflow-es - 如何提取用户在上一个意图中给出的特定值并在对话流中的下一个意图中使用它?