How To Create a Contact Form. Here’s an example of a simple contact form in HTML and PHP that you can use to send an email:
HTML Form:
<form method="post" action="send_email.php"> <label for="name">Name:</label> <input type="text" id="name" name="name" required> <label for="email">Email:</label> <input type="email" id="email" name="email" required> <label for="subject">Subject:</label> <input type="text" id="subject" name="subject" required> <label for="message">Message:</label> <textarea id="message" name="message" required></textarea> <input type="submit" value="Send"> </form>
PHP Script (send_email.php):
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = $_POST["name"]; $email = $_POST["email"]; $subject = $_POST["subject"]; $message = $_POST["message"]; $to = "your_email@example.com"; $headers = "From: $email\r\n"; $headers .= "Reply-To: $email\r\n"; $headers .= "Content-type: text/plain\r\n"; $body = "Name: $name\n"; $body .= "Email: $email\n"; $body .= "Subject: $subject\n\n"; $body .= "Message:\n$message"; if (mail($to, $subject, $body, $headers)) { echo "Thank you for contacting us!"; } else { echo "There was an error sending your message. Please try again later."; } } ?>
Replace your_email@example.com
with your email address where you want to receive the message.
This code is a simple example of how to send an email using PHP’s built-in mail()
function. However, keep in mind that sending email from a web server can be tricky, and you may need to configure your server properly to ensure that your messages are not blocked by spam filters or rejected by email providers. Additionally, this code does not include any form of validation or sanitization of user inputs, so it may be susceptible to security vulnerabilities. It’s important to properly validate and sanitize any user input before using it in your code.