Why You Need a Contact Form on Your Website
In today’s web development landscape, a contact form is an essential communication tool for both businesses and personal websites. It allows users to reach out conveniently while helping site owners manage inquiries efficiently. This tutorial walks you through how to build a contact form that sends messages via email using PHP and the PHPMailer library.
Step 1: Set Up Your Development Environment
Before writing any code, make sure the following components are installed and configured properly:
- The latest version of PHP;
- [PHPMailer](https://github.com/PHPMailer/PHPMailer) library (recommended to install via Composer).
Use the following Composer command to install PHPMailer:
<span class="fun">composer require phpmailer/phpmailer</span>
Step 2: Create the HTML Contact Form
Next, build a simple HTML form where users can input their name, email, and message. The form will send data via the POST method to a PHP handler:
<form action="sendmail.php" method="post">
<input type="text" name="name" placeholder="Your Name" required>
<input type="email" name="email" placeholder="Your Email" required>
<textarea name="message" placeholder="Your Message" required></textarea>
<input type="submit" value="Send Message">
</form>
Step 3: Handle the Form Submission with PHP
Create a `sendmail.php` file to handle form submissions. It will use PHPMailer to send the submitted data via email:
<?php
require 'PHPMailer/PHPMailerAutoload.php';
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.example.com'; // Mail server
$mail->SMTPAuth = true;
$mail->Username = 'your-email@example.com'; // Sender's email
$mail->Password = 'your-email-password'; // Sender's email password
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('your-email@example.com', 'Your Name');
$mail->addAddress('recipient@example.com'); // Recipient's email
$mail->isHTML(true);
$mail->Subject = 'New Message from Contact Form';
$mail->Body = "Name: $name<br>Email: $email<br>Message: $message";
if(!$mail->send()) {
echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent successfully!';
}
?>
Make sure to replace the SMTP host, sender address, password, and recipient address with your actual settings.
Step 4: Testing and Deployment
Upload the HTML and PHP files to your web server. Then, open the page with the contact form in your browser, fill out the fields, and click “Send Message.” If everything is set up correctly, you’ll see a success message, and a new email will be delivered to your inbox.
Conclusion
With PHP and PHPMailer, you can easily implement a professional contact form for your website. This allows users to reach out to you seamlessly. You can further enhance the form by adding input validation, CAPTCHA, or additional fields as needed.