Php html form data to email
A classic!
Here's a simple example of how to send HTML form data to an email using PHP:
HTML Form
<form action="send_email.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 (send_email.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\n";
$headers.= "Reply-To: $email\r\n";
$headers.= "MIME-Version: 1.0\r\n";
$headers.= "Content-Type: text/html; charset=UTF-8\r\n";
// Set the email body
$body = "<html><body>";
$body.= "<h2>Contact Form Submission</h2>";
$body.= "<p>Name: $name</p>";
$body.= "<p>Email: $email</p>";
$body.= "<p>Message:</p>";
$body.= "<p>$message</p>";
$body.= "</body></html>";
// Send the email
if (mail($to, $subject, $body, $headers)) {
echo "Email sent successfully!";
} else {
echo "Error sending email.";
}
}
?>
Here's what's happening:
- The HTML form is submitted to the
send_email.php
script using thePOST
method. - The script checks if the form has been submitted using
$_SERVER["REQUEST_METHOD"] == "POST"
. - If the form has been submitted, the script gets the form data using
$_POST
. - The script sets the email headers using
mail()
function. - The script sets the email body using HTML.
- The script sends the email using
mail()
function. - If the email is sent successfully, the script displays a success message. If there's an error, it displays an error message.
Note: Make sure to replace [email protected]
with your actual email address. Also, this is a basic example, and you may want to add more error handling and validation to your script.