Ajax mail send

AJAX (Asynchronous JavaScript and XML) is a technique used to send and receive data from a server without reloading the entire web page. Here's an example of how to send an email using AJAX:

HTML

<form id="email-form">
  <input type="text" id="email-to" placeholder="Email to">
  <input type="text" id="email-subject" placeholder="Subject">
  <textarea id="email-body"></textarea>
  <button id="send-email">Send</button>
</form>

JavaScript

const form = document.getElementById('email-form');
const sendEmailButton = document.getElementById('send-email');

sendEmailButton.addEventListener('click', (e) => {
  e.preventDefault();
  const to = document.getElementById('email-to').value;
  const subject = document.getElementById('email-subject').value;
  const body = document.getElementById('email-body').value;

  const xhr = new XMLHttpRequest();
  xhr.open('POST', 'send-email.php', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

  xhr.onload = function() {
    if (xhr.status === 200) {
      console.log('Email sent successfully!');
    } else {
      console.log('Error sending email:', xhr.statusText);
    }
  };

  xhr.send(`to=${to}&subject=${subject}&body=${body}`);
});

PHP (send-email.php)

<?php
  // Configuration
  $email_from = '[email protected]';
  $email_password = 'your-email-password';
  $smtp_server = 'smtp.example.com';
  $smtp_port = 587;

  // Get the email data from the AJAX request
  $to = $_POST['to'];
  $subject = $_POST['subject'];
  $body = $_POST['body'];

  // Create a new PHPMailer object
  $mail = new PHPMailer\PHPMailer\PHPMailer();
  $mail->isSMTP();
  $mail->Host = $smtp_server;
  $mail->Port = $smtp_port;
  $mail->SMTPAuth = true;
  $mail->Username = $email_from;
  $mail->Password = $email_password;

  // Set the email message
  $mail->setFrom($email_from);
  $mail->addAddress($to);
  $mail->Subject = $subject;
  $mail->Body = $body;

  // Send the email
  if (!$mail->send()) {
    echo 'Error sending email: '. $mail->ErrorInfo;
  } else {
    echo 'Email sent successfully!';
  }
?>

In this example, we create a form with input fields for the email to, subject, and body. When the user clicks the "Send" button, the JavaScript code sends an AJAX request to the send-email.php script, which sends the email using the PHPMailer library.

Note that you'll need to install the PHPMailer library and configure your email settings in the send-email.php script. You'll also need to modify the script to match your specific email server settings.

Also, keep in mind that this is just a basic example, and you should consider implementing additional security measures, such as validating user input and preventing spam, to ensure that your email sending functionality is secure and reliable.