0

When I just put the next code into HTML it works perfectly:

<?php
$name = 'My name';
$email = 'myemail@gmail.com';
$headers = "From: contact@mywebsite.com";
$to = 'contact@mywebsite.com';
$message = 'My message';
$subject = 'Message from Contact Form';

$send_email = wp_mail($to,$subject,$message,$headers);

if ($send_email == false) {
    echo 'this is error';
} else {
    echo 'this is success';
}
?>

It indeed works and echo 'this is success'.

But if I put it to a separate email.php and add into index.php the next Ajax code:

$(document).ready(function () {
  $(".myform").on("submit", function () {
    var form = $(this);
    $.ajax({
      url: "https://mywebsite.com/wp-content/themes/mytheme/email.php",
      method: form.attr("method"),
      data: form.serialize(),
      success: function (result) {
        console.log(result);
      },
    });
    return false;
  });
});

It already doesn't return anything. Console Log doesn't show anything. Once I change wp_mail() function into email.php to a regular mail() function - everything starts to work perfectly again and console log shows 'this is success'. Also I don't get emails when I use wp_mail() in a separate email.php with Ajax but I do get them when I use wp_mail() in index.php without Ajax.

Please let me know how to fix it. Why does it work with mail() but doesn't with wp_mail()? And why does wp_mail() work perfectly without Ajax into index.php, but doesn't with Ajax on a separate email.php?

PS: I removed all HTML forms into the code specially to simplify the code.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • Check the actual response in your browser dev-tools _Network_ panel. Chances are you're not including some vital Wordpress files and `wp_mail` is not defined. You should be using an [AJAX hook](https://developer.wordpress.org/plugins/javascript/ajax/) – Phil Jun 10 '22 at 00:48
  • wp_mail is built on top of PHPMailer rather than php's mail. It sends emails in a very different manner. You'll need to provide WordPress with SMTP information. You can do that such as through wp-config.php, with a hook in your functions.php, or through a plugin, etc. But trying to tap into the ease of PHP's mail function, doesn't provide functionality that PHPMailer or wp_email provides and thus they behave in a very different way. If you want to roll with wp_mail, you'll need to provide it with the credentials it needs. – Kevin Y Jun 10 '22 at 00:50

0 Answers0