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:
- The form is displayed using HTML and PHP.
- When the form is submitted, the
$_SERVER["REQUEST_METHOD"]
variable checks if the request method is "POST". - If it is, the form data is retrieved using
$_POST
variables. - The email headers and body are set using PHP variables.
- The
mail()
function is used to send the email. - If the email is sent successfully, a success message is displayed. If not, an error message is displayed.
Note:
- Make sure to replace
[email protected]
with the actual email address you want to receive the form submissions. - This is a very basic example and you may want to add more validation and error handling to your form.
- The
mail()
function is not reliable and may not work on all servers. You may want to consider using a more reliable email sending library or service.