Mail php form

Here is an example of how to create a simple PHP form that sends an email using the mail() function:

index.php

<?php
// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  // Get the form data
  $name = $_POST["name"];
  $email = $_POST["email"];
  $message = $_POST["message"];

  // Set the email headers
  $to = "[email protected]";
  $subject = "Contact Form Submission";
  $headers = "From: $email\r\nReply-To: $email\r\n";

  // Set the email body
  $body = "Name: $name\nEmail: $email\nMessage: $message";

  // Send the email
  if (mail($to, $subject, $body, $headers)) {
    echo "Email sent successfully!";
  } else {
    echo "Error sending email!";
  }
} else {
  // Display the form
 ?>
  <form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name"><br><br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email"><br><br>
    <label for="message">Message:</label>
    <textarea id="message" name="message"></textarea><br><br>
    <input type="submit" value="Send">
  </form>
  <?php
}
?>

How it works:

  1. The form is displayed using HTML and PHP.
  2. When the form is submitted, the $_SERVER["REQUEST_METHOD"] variable checks if the request method is "POST".
  3. If it is, the form data is retrieved using $_POST variables.
  4. The email headers and body are set using PHP variables.
  5. The mail() function is used to send the email.
  6. If the email is sent successfully, a success message is displayed. If not, an error message is displayed.

Note: