Create a new file named send_email.php in the same directory as your HTML file.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get form data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$subject = htmlspecialchars($_POST['subject']);
$message = htmlspecialchars($_POST['message']);
// Your email address where you want to receive the emails
$recipient_email = "[email protected]"; // *** REPLACE WITH YOUR EMAIL ADDRESS ***
// Email subject
$email_subject = "New Contact Form Submission: " . $subject;
// Email body
$email_body = "You have received a new message from your website contact form.\n\n";
$email_body .= "Name: " . $name . "\n";
$email_body .= "Email: " . $email . "\n";
$email_body .= "Message:\n" . $message . "\n";
// Headers for the email
$headers = "From: " . $name . " <" . $email . ">\r\n";
$headers .= "Reply-To: " . $email . "\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();
// Send the email
if (mail($recipient_email, $email_subject, $email_body, $headers)) {
// Redirect to a thank you page or display a success message
echo "<p>Thank you for your message. It has been sent successfully!</p>";
// Or redirect: header("Location: thank_you.html");
} else {
// Display an error message
echo "<p>An error occurred while sending your message. Please try again later.</p>";
}
} else {
// If accessed directly without POST request
echo "<p>Invalid request.</p>";
}
?>
Note: Emails sent via the mail() function can sometimes be flagged as spam.