Form mail php

Form mail in PHP!

Form mail is a common feature in web development where a user submits a form on a website, and the data is sent to a server-side script (usually written in PHP) to process and send an email with the form data.

Here's a basic example of how to create a form mail script in PHP:

HTML Form

<form action="sendmail.php" 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 Script (sendmail.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 and body
  $to = "[email protected]"; // Replace with your email address
  $subject = "Form Submission from ". $name;
  $body = "Name: ". $name. "\n";
  $body.= "Email: ". $email. "\n";
  $body.= "Message: ". $message;

  // Send the email using PHP's mail function
  $headers = "From: ". $email. "\r\n";
  $headers.= "Reply-To: ". $email. "\r\n";
  $headers.= "MIME-Version: 1.0\r\n";
  $headers.= "Content-Type: text/plain; charset=UTF-8\r\n";
  mail($to, $subject, $body, $headers);

  // Display a success message
  echo "Thank you for submitting the form!";
} else {
  // Display the form if it hasn't been submitted
 ?>
  <form action="sendmail.php" method="post">
    <!-- Form fields go here -->
  </form>
  <?php
}
?>

In this example, the form is submitted to the sendmail.php script, which checks if the form has been submitted using the $_SERVER["REQUEST_METHOD"] variable. If the form has been submitted, it retrieves the form data using the $_POST superglobal and sets the email headers and body. The email is then sent using PHP's mail function. Finally, a success message is displayed.

Note that this is a basic example and you should consider implementing additional security measures, such as validating user input and preventing spam submissions.