0

am using Mail PHP to send mails. I must use an external SMTP so I have added PHP Mailer.

The problem is that a successful message don't come back to the form.

This is the code

$output = json_encode(array('type'=>'message', 'text' => 'Ciao '.$user_Name .', grazie per averci contattato.'));
die($output);   


$mail->Send();

If I put first Mail Send, the mail is sent but the successful message is not shown.

If I put first json_encode, the message is shown but the mail is not sent

I also tried with this code

$output = json_encode(array('type'=>'message', 'text' => 'Ciao '.$user_Name .', grazie per averci contattato.'));
echo($output);   
return;

But it doesn't work.

update

I tried again, but the success message is not passed (the mail arrives correctly though)

If it helps, this is the full code

<?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); 
}


}
?>

This is the orginal code

<?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);
    }
}
?>
mw509
  • 1,957
  • 1
  • 19
  • 25
2CANadv
  • 17
  • 3
  • 1
    Of course nothing more happens after you call `die`. And “don't work” doesn’t help us understand what your actual problem is. Please go read [ask] and [mre], and then edit your question accordingly. – CBroe Mar 04 '20 at 12:17
  • I think you are trying to get response by ajax! please edit your question and add your full codes in. –  Mar 04 '20 at 12:18
  • 1
    _“The problem is that the succesful message dont' come back to the form.”_ - I think the even bigger problem is, that your “success” message currently doesn’t care in the slightest, whether sending that mail _actually_ succeeded or not. Your response back to the client should take the return value `$mail->Send()` into account … – CBroe Mar 04 '20 at 12:19
  • You are trying to execute code after die method. what that actually mean? put $mail->SMTPDebug = 1; or $mail->SMTPDebug = 2; to see the exact errors. then take decision. – Ariful Islam Mar 04 '20 at 12:21
  • if i use $mail->Send(); the successful message is not shown in the form, if i comment the send function the message works. It seems that sending blocks everything – 2CANadv Mar 04 '20 at 13:23
  • Constant [FILTER_SANITIZE_STRING](https://stackoverflow.com/questions/69207368/constant-filter-sanitize-string-is-deprecated) is deprecated. Please stop using it. – Dharman Nov 15 '21 at 12:38

1 Answers1

0

You might want to check if the mail is sent before performing other actions. so with the code below, a check is made on $mail->send() if this action does not return true, it means it failed and we can do something else. Else, we can go ahead and work on our 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); 
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Full Stop
  • 904
  • 11
  • 24
  • i replied in another comment – 2CANadv Mar 04 '20 at 13:29
  • @mw509 have you see the full code i posted? Thank's – 2CANadv Mar 05 '20 at 09:30
  • Yes I have. You could add updates to your first question instead of as an answer. I have fixed that for you. Now, on your question, I do not see a success message in your code but I do see that in the condition, should it fail or succeed you display $output with die. which is not a good idea but am sure you have your reasons for that. My question though is, what do you want to see as a success message? – mw509 Mar 05 '20 at 10:43
  • i change die with: $output = json_encode(array('type'=>'message', 'text' => 'Ciao '.$user_Name .', grazie per averci contattato.')); echo($output); The succesful message should show in index.html, before the form. – 2CANadv Mar 05 '20 at 11:23
  • if i dont do mail->send() the message work end is shown in index.html before form – 2CANadv Mar 05 '20 at 11:25