Mail form php

Here is an example of a simple mail form in PHP:

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"];

  // Validate the form data
  if (empty($name) || empty($email) || empty($message)) {
    $error = "Please fill out all fields";
  } else {
    // Send the email
    $to = "[email protected]";
    $subject = "Contact Form Submission";
    $body = "Name: $name\nEmail: $email\nMessage: $message";
    mail($to, $subject, $body);
    $success = "Thank you for contacting us!";
  }
}
?>

<!-- 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>

<!-- Display any error or success messages -->
<?php if (isset($error)) {?>
  <p style="color: red;"><?php echo $error;?></p>
<?php } elseif (isset($success)) {?>
  <p style="color: green;"><?php echo $success;?></p>
<?php }?>

This code checks if the form has been submitted, and if so, it gets the form data, validates it, and sends an email to the specified address. If there are any errors, it displays an error message. If the email is sent successfully, it displays a success message.

Note: This is a very basic example, and you should consider adding more validation and security measures to your form handling code.

Also, you need to replace [email protected] with the actual email address you want to receive the form submissions.

You can also use PHPMailer library which is more powerful and flexible than the built-in mail() function.

<?php
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');

$mail->Subject = 'Contact Form Submission';
$mail->Body = 'Name: '. $_POST["name"]. "\nEmail: ". $_POST["email"]. "\nMessage: ". $_POST["message"];

if (!$mail->send()) {
    echo 'Error: '. $mail->ErrorInfo;
} else {
    echo 'Message sent!';
}
?>

You can also use other libraries like SwiftMailer, etc.