To send form data from a PHP script to an email address and format it as an HTML email, you can use the following code:
<?php
if(isset($_POST['submit'])){
// Collect form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Set up email parameters
$to = "youremail@example.com"; // Your email address
$subject = "New message from website";
$headers = "From: " . $name . " <" . $email . ">\r\n";
$headers .= "Reply-To: " . $email . "\r\n";
$headers .= "Content-type: text/html\r\n";
// Construct the email message
$message = "
<html>
<head>
<title>New message from website</title>
</head>
<body>
<h2>New message from website contact form:</h2>
<p><strong>Name:</strong> $name</p>
<p><strong>Email:</strong> $email</p>
<p><strong>Message:</strong> $message</p>
</body>
</html>
";
// Send the email
mail($to, $subject, $message, $headers);
// Redirect to a thank you page
header("Location: thankyou.html");
}
?>
This code checks if the form has been submitted and collects the form data using $_POST. It then sets up the email parameters, including the recipient email address, subject, and headers. The email message is constructed as an HTML message with the form data inserted, and then sent using the mail() function.
Note that the mail() function may not work on all servers or may be blocked by spam filters. It’s also important to validate and sanitize the form data to prevent security issues such as SQL injection or cross-site scripting (XSS) attacks.
