检测PHP Mailer错误并使用jquery在网站上打印消息

时间:2017-08-01 12:50:03

标签: javascript php jquery phpmailer

我正在使用PhpMailer发送电子邮件。在我自己的脚本中,我想在下面的if语句中解析一些javascript。请注意,我已启用html。

当电子邮件未发送时,我想在.done函数中解析一些未发送电子邮件的javascript。例如complete.html("Message Not Sent!");发送电子邮件时,我想显示电子邮件已发送。我怎么能这样做,哪里更好,在PHP文件内或在JavaScript中?

 var form = $('#contact');
    form.submit(function(event) {
      event.preventDefault();
      var complete = $('#formAppend');
      var $form = $(this);
      var name = $("#fname").val();
      var email = $("#email").val();
      var Message = $("#msg").val();
      var countryoption = $("#country").val();
      $.ajax({
          type: 'POST',
          url: '../sendemail.php',
          data: {
            Name: name,
            Email: email,
            message: Message,
            Country: countryoption
          },
          beforeSend: function() {
            complete.html('Message is Sending...').fadeIn();
          }
        })
        .done(function(data) {
//This should change depending on the php if statement at the bottom.
          complete.html("Message Sent");
        });
    }); //end contact form
<form id="contact" method="post" action="#ss">
  <div id="formAppend"></div>
  <input type="text" id="fname" name="firstname" placeholder="Το όνομα σας.." required>
  <input type="email" id="email" name="email" placeholder="Το email σας.." required>
  <select id="country" required>
      <option class="w3-center" value="" disabled selected value>-- Χώρα --</option>
      <option value="Κυπρος">Κύπρος</option>
      <option value="Ελλάδα">Ελλάδα</option>
      <option value="Άλλο">Άλλη</option>
  </select>
  <textarea id="msg" name="message" placeholder="Γράψε το μήνυμα.." style="height:200px;max-height:400px;min-height:100px;" required></textarea>
  <div id="op">
    <button type="submit" style="" class="btn btn-primary img-responsive"> Αποστολή</button> </div>
</form>

PHP:

<?php
require 'PHPMailer-master/PHPMailerAutoload.php';



    if(empty($_POST['Email'])){
        $_POST['Email']= "";
    }
    if(empty($_POST['Name'])){
        $_POST['Name']= "";
    }

    if(empty($_POST['message'])){
        $_POST['message']= "";
    }


if (isset($_POST["message"]) && !empty($_POST["message"])) {

   $mymail=smtpmailer("webdominar1@gmail.com",$_POST['Email'], $_POST['Name'], $_POST['message']);    


}else{  
    header('Location: http://webdominar.xyz'); exit();

}



function smtpmailer($to, $from, $from_name, $body) {
    $mail = new PHPMailer;
    $mail->isSMTP();
    $mail->Debugoutput = 'html';
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;
    $mail->SMTPSecure = 'tls';
    $mail->SMTPAuth = true;
    $mail->Username = '';  
    $mail->Password = '';          
    $mail->SetFrom($from, $from_name);
    $mail->Subject = "Εμβολιασμός Δέντρων ~ Φόρμα Επικοινωνίας ~ $body ";
    $mail->CharSet  = 'UTF-8';
    $mail->isHTML(true);                                  // Set email format to HTML
    $Country = $_POST["Country"]; 
    $mail->Body = "BLABLA ";//end email body




    $mail->AddAddress($to);
//send the message, check for errors
if (!$mail->send()) { //Message not sent
    echo "Mailer Error: " . $mail->ErrorInfo;

} else {//Message sent!
    echo "Well done $from_name, your message has been sent!\nWe will reply to the following email: $from"
            . "<br>Your Message: $body";
}




} //end function smtpmailer



?>

2 个答案:

答案 0 :(得分:0)

将PHP的结尾更改为:

header("Content-type:application/json"); 
$message = "Well done ".$from_name.", your message has been sent!<br/>We will reply to the following email:".$from."<br>Your Message: ".$body;
if (!$mail->send()) {     
  echo '{"error":"'.$mail->ErrorInfo.'"}';
} else {
  echo '{"success":"'.json_encode($message).'"}';
} 

然后您可以在.done

中执行此操作
.done(function(data) {
    if (data.error) { 
     complete.html(data.error).addClass("error"); 
    }
    else  
      complete.html(JSON.parse(data.success));
    }
});

答案 1 :(得分:0)

像这样改变PHP和JS代码........

require 'PHPMailer-master/PHPMailerAutoload.php';
if (empty($_POST['Email'])) {
    $_POST['Email'] = "";
}
if (empty($_POST['Name'])) {
    $_POST['Name'] = "";
}

if (empty($_POST['message'])) {
    $_POST['message'] = "";
}


if (isset($_POST["message"]) && !empty($_POST["message"])) {

    $mymail = smtpmailer("webdominar1@gmail.com", $_POST['Email'], $_POST['Name'], $_POST['message']);
} else {
    header('Location: http://webdominar.xyz');
    exit();
}

function smtpmailer($to, $from, $from_name, $body) {
    $mail = new PHPMailer;
    $mail->isSMTP();
    $mail->Debugoutput = 'html';
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;
    $mail->SMTPSecure = 'tls';
    $mail->SMTPAuth = true;
    $mail->Username = '';
    $mail->Password = '';
    $mail->SetFrom($from, $from_name);
    $mail->Subject = "Εμβολιασμός Δέντρων ~ Φόρμα Επικοινωνίας ~ $body ";
    $mail->CharSet = 'UTF-8';
    $mail->isHTML(true);                                  // Set email format to HTML
    $Country = $_POST["Country"];
    $mail->Body = "BLABLA "; //end email body




    $mail->AddAddress($to);
//send the message, check for errors
    if (!$mail->send()) { //Message not sent
        //echo "Mailer Error: " . $mail->ErrorInfo;
        $responce = array(
            'message' => $mail->ErrorInfo,
            'success' => FALSE,
        );
        echo json_encode($responce);
    } else {//Message sent!
        $msg = "Well done $from_name, your message has been sent!\nWe will reply to the following email: $from"
                . "<br>Your Message: $body";
        $responce = array(
            'message' => $msg,
            'success' => TRUE,
        );
        echo json_encode($responce);
    }
}

像这样更改你的JS代码

var form = $('#contact');
    form.submit(function(event) {
      event.preventDefault();
      var complete = $('#formAppend');
      var $form = $(this);
      var name = $("#fname").val();
      var email = $("#email").val();
      var Message = $("#msg").val();
      var countryoption = $("#country").val();
      $.ajax({
          type: 'POST',
          url: '../sendemail.php',
          data: {
            Name: name,
            Email: email,
            message: Message,
            Country: countryoption
          },
          beforeSend: function() {
            complete.html('Message is Sending...').fadeIn();
          }
        })
        .done(function(data) {
            var response=JSON.parse(data); 
            if(response.success == true) {
                //return true
                complete.html("Message Sent");
                // if you want show Response message which get form sendemail.php
                complete.html(data.message);
            } else {
                //return false
                complete.html("Message Not Sent!");
                // if you want show Response message which get form sendemail.php
                complete.html(data.message)
            }
//This should change depending on the php if statement at the bottom.

        });
    }); //end contact form