【问题标题】:PHP Mailer & AjaxPHP 邮件程序和 Ajax
【发布时间】:2020-03-04 12:14:38
【问题描述】:

我正在使用 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);
    }
}
?>

【问题讨论】:

  • 当然,在您致电die 后不会再发生任何事情。 “不工作”并不能帮助我们了解您的实际问题是什么。请阅读How to Askminimal reproducible example,然后相应地编辑您的问题。
  • 我认为您正试图通过 ajax 获得响应!请编辑您的问题并添加您的完整代码。
  • “问题是成功的消息不会'回到表单中。” - 我认为更大的问题是,你的“成功”消息目前没有'丝毫不在乎发送该邮件实际上是否成功。您对客户的回复应考虑返回值$mail-&gt;Send() ...
  • 您正在尝试在 die 方法之后执行代码。那实际上是什么意思?把 $mail->SMTPDebug = 1;或 $mail->SMTPDebug = 2;查看确切的错误。然后做出决定。
  • 如果我使用 $mail->Send();成功的消息未显示在表单中,如果我评论发送功能消息有效。似乎发送会阻止一切

标签: php ajax phpmailer


【解决方案1】:

您可能想在执行其他操作之前检查邮件是否已发送。因此,使用下面的代码,对$mail-&gt;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); 
}

【讨论】:

  • 我在另一条评论中回复了
  • @mw509 你看到我发布的完整代码了吗?谢谢
  • 是的,我有。您可以将更新添加到您的第一个问题,而不是作为答案。我已经为你解决了。现在,关于您的问题,我在您的代码中没有看到成功消息,但我确实看到在这种情况下,如果它失败或成功,您将显示 $output 和 die。这不是一个好主意,但我相信你有你的理由。不过我的问题是,您希望看到什么作为成功信息?
  • 我用:$output = json_encode(array('type'=>'message', 'text' => 'Ciao '.$user_Name .', grazie per averci contattato.') );回声($输出);成功的消息应该显示在 index.html 中,在表单之前。
  • 如果我不做 mail->send() 消息工作结束显示在 index.html 表格之前
猜你喜欢
  • 2017-12-12
  • 2010-12-20
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-14
  • 2016-07-31
  • 2011-01-14
相关资源
最近更新 更多