Welcome to this comprehensive guide on creating a PHP contact form that sends emails! In this tutorial, we'll cover everything from setting up your form to sending emails with real-world examples. By the end of this guide, you'll be able to build your own contact forms and integrate them into your websites. π‘ Let's get started!
A contact form is a crucial part of any website that allows users to reach out to the website owner by submitting their message. In this tutorial, we'll create a simple contact form and implement an email feature to send the user's message to the website owner.
Before we dive into the PHP code, let's set up our contact form using HTML.
<form action="send_email.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" required><br>
<label for="email">Email:</label>
<input type="email" name="email" required><br>
<label for="message">Message:</label>
<textarea name="message" rows="5" cols="30" required></textarea><br>
<input type="submit" value="Submit">
</form>This is a basic contact form that collects the user's name, email, and message. The form submits the data to send_email.php when the user clicks the "Submit" button.
Now, let's write the PHP script (send_email.php) that receives the form data and sends an email with the user's message.
<?php
// Replace the following variables with your own email information
$to_email = 'youremail@example.com';
$subject = 'New Contact Form Submission';
// Get the form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Create the email headers
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "Content-type: text/plain; charset=UTF-8\r\n";
// Send the email
if (mail($to_email, $subject, $message, $headers)) {
echo 'Email sent successfully!';
} else {
echo 'Error: Email could not be sent.';
}
?>In this script, we first set the recipient's email, subject, and get the form data sent from the HTML form. Then, we create email headers and send the email using the mail() function.
Now, save both the HTML and PHP files in the same directory, and open the HTML file in your web browser. Fill out the form and submit it to test the email functionality.
How can you test the contact form once it's set up?
That's it! You've now learned how to create a PHP contact form that sends emails. This skill is valuable for building interactive and engaging websites for users. Happy coding! π‘π―