PHP – Use Case 5: Sending Emails Using PHP (Contact Form with Email Notification)
Project Overview
Implementing a Contact Form with Email Notifications allows users to send messages directly from your website, which are then emailed to a designated recipient. This project covers form handling, input validation, email sending using PHP’s mail()
function, and security best practices.
Prerequisites
Ensure you have the following:
- Web Server: Apache (using XAMPP, WAMP, or MAMP)
- PHP: Version 7.4 or higher
- Code Editor: VS Code, Sublime Text, PHPStorm, etc.
- Email Server Configuration: For sending emails (PHP’s
mail()
function requires a configured mail server; alternatively, use libraries like PHPMailer for SMTP).
Step-by-Step Procedure
1. Setting Up the Development Environment
- Install XAMPP:
- Download from XAMPP Official Website.
- Follow the installation wizard and install it in the default directory.
- Start Apache:
- Open the XAMPP Control Panel.
- Start the Apache module.
2. Creating the Project Structure
Organize your project files as follows:
contact-form/
├── assets/
│ ├── css/
│ │ └── styles.css
│ └── js/
│ └── scripts.js
├── templates/
│ ├── header.php
│ └── footer.php
├── contact.php
├── send_mail.php
└── README.md
3. Creating Reusable Templates
a. Header (templates/header.php
)
<?php
// templates/header.php
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Us</title>
<link rel="stylesheet" href="/contact-form/assets/css/styles.css">
</head>
<body>
<header>
<h1>Contact Us</h1>
<nav>
<a href="/contact-form/contact.php">Home</a>
</nav>
</header>
<main>
b. Footer (templates/footer.php
)
<?php
// templates/footer.php
?>
</main>
<footer>
<p>© <?php echo date("Y"); ?> Your Company Name</p>
</footer>
<script src="/contact-form/assets/js/scripts.js"></script>
</body>
</html>
4. Styling the Application (assets/css/styles.css
)
Add basic styles to enhance the appearance.
/* assets/css/styles.css */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header, footer {
background-color: #0066cc;
color: #fff;
padding: 10px 20px;
}
header h1, footer p {
margin: 0;
}
nav a {
color: #fff;
margin-right: 15px;
text-decoration: none;
}
main {
padding: 20px;
}
form {
max-width: 600px;
margin: auto;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input[type="text"],
input[type="email"],
textarea {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
button {
padding: 10px 15px;
background-color: #28a745;
color: #fff;
border: none;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
.error {
background-color: #f8d7da;
color: #842029;
padding: 15px;
margin-bottom: 20px;
border: 1px solid #f5c2c7;
border-radius: 4px;
}
.success {
background-color: #d1e7dd;
color: #0f5132;
padding: 15px;
margin-bottom: 20px;
border: 1px solid #badbcc;
border-radius: 4px;
}
5. Building the Contact Form (contact.php
)
This page allows users to submit their contact information.
<?php
// contact.php
require 'templates/header.php';
$errors = [];
$success = '';
// Retrieve previous input values if available
$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$message = $_POST['message'] ?? '';
?>
<h2>Get in Touch</h2>
<?php if (!empty($errors)): ?>
<div class="error">
<ul>
<?php foreach($errors as $error): ?>
<li><?php echo htmlspecialchars($error); ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php if ($success): ?>
<div class="success">
<p><?php echo htmlspecialchars($success); ?></p>
</div>
<?php endif; ?>
<form action="send_mail.php" method="POST">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<?php echo htmlspecialchars($name); ?>" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="<?php echo htmlspecialchars($email); ?>" required>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea id="message" name="message" rows="8" required><?php echo htmlspecialchars($message); ?></textarea>
</div>
<button type="submit">Send Message</button>
</form>
<?php
require 'templates/footer.php';
?>
6. Handling Form Submission and Sending Email (send_mail.php
)
This script processes the form data, validates inputs, and sends an email using PHP’s mail()
function.
<?php
// send_mail.php
require 'templates/header.php';
$errors = [];
$success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Sanitize and validate inputs
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$message = trim($_POST['message']);
if (empty($name)) {
$errors[] = 'Name is required.';
}
if (empty($email)) {
$errors[] = 'Email is required.';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email format.';
}
if (empty($message)) {
$errors[] = 'Message is required.';
}
if (empty($errors)) {
// Prepare email
$to = 'your_email@example.com'; // Replace with your email address
$subject = "New Contact Form Submission from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
$email_headers = "From: $name <$email>";
// Send email
if (mail($to, $subject, $email_content, $email_headers)) {
$success = 'Thank you! Your message has been sent.';
// Clear form fields
$name = $email = $message = '';
} else {
$errors[] = 'There was a problem sending your message. Please try again later.';
}
}
} else {
// Redirect to contact form if accessed directly
header('Location: contact.php');
exit;
}
?>
<h2>Contact Us</h2>
<?php if (!empty($errors)): ?>
<div class="error">
<ul>
<?php foreach($errors as $error): ?>
<li><?php echo htmlspecialchars($error); ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php if ($success): ?>
<div class="success">
<p><?php echo htmlspecialchars($success); ?></p>
</div>
<?php endif; ?>
<a href="contact.php">Back to Contact Form</a>
<?php
require 'templates/footer.php';
?>
Note: PHP’s mail()
function relies on a properly configured mail server. On local environments like XAMPP, emails might not be sent by default. To reliably send emails, consider using a mailing library like PHPMailer with SMTP.
7. Enhancing Email Functionality with PHPMailer (Optional)
Using PHPMailer provides more control and reliability when sending emails via SMTP.
a. Installing PHPMailer via Composer
- Initialize Composer:
- Navigate to your project directory in the terminal.
- Run
composer init
and follow the prompts.
- Install PHPMailer:
composer require phpmailer/phpmailer
b. Updating Email Sending in send_mail.php
<?php
// send_mail.php (Using PHPMailer)
require 'templates/header.php';
require 'vendor/autoload.php'; // Composer's autoloader
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$errors = [];
$success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Sanitize and validate inputs
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$message = trim($_POST['message']);
if (empty($name)) {
$errors[] = 'Name is required.';
}
if (empty($email)) {
$errors[] = 'Email is required.';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email format.';
}
if (empty($message)) {
$errors[] = 'Message is required.';
}
if (empty($errors)) {
// Initialize PHPMailer
$mail = new PHPMailer(true);
try {
// Server settings
//$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.example.com'; // Set the SMTP server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'your_email@example.com'; // SMTP username
$mail->Password = 'your_email_password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption
$mail->Port = 587; // TCP port to connect to
// Recipients
$mail->setFrom('no-reply@yourdomain.com', 'Your Company');
$mail->addAddress('your_email@example.com', 'Your Name'); // Add a recipient
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = "New Contact Form Submission from $name";
$mail->Body = "<p><strong>Name:</strong> {$name}</p>
<p><strong>Email:</strong> {$email}</p>
<p><strong>Message:</strong><br>" . nl2br(htmlspecialchars($message)) . "</p>";
$mail->AltBody = "Name: {$name}\nEmail: {$email}\nMessage:\n{$message}";
$mail->send();
$success = 'Thank you! Your message has been sent.';
// Clear form fields
$name = $email = $message = '';
} catch (Exception $e) {
$errors[] = "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
} else {
// Redirect to contact form if accessed directly
header('Location: contact.php');
exit;
}
?>
<h2>Contact Us</h2>
<?php if (!empty($errors)): ?>
<div class="error">
<ul>
<?php foreach($errors as $error): ?>
<li><?php echo htmlspecialchars($error); ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php if ($success): ?>
<div class="success">
<p><?php echo htmlspecialchars($success); ?></p>
</div>
<?php endif; ?>
<a href="contact.php">Back to Contact Form</a>
<?php
require 'templates/footer.php';
?>
Note:
- Replace
'smtp.example.com'
,'your_email@example.com'
, and'your_email_password'
with your SMTP server details. - Ensure that your SMTP credentials are correct and that your hosting provider allows SMTP connections.
- Consider storing sensitive information like SMTP credentials in environment variables or secure configuration files.
8. Testing the Application
- Access the Contact Form:
- Navigate to
http://localhost/contact-form/contact.php
. - Fill in the form and submit.
- Verify that the success message appears and check if the email is received.
- Navigate to
- Handle Errors:
- Try submitting the form with incomplete or invalid data to ensure validation works.
- Verify that error messages are displayed appropriately.
- Check Email Functionality:
- If using PHP’s
mail()
function, ensure that emails are sent correctly (may require mail server configuration). - If using PHPMailer, verify SMTP settings and ensure emails are delivered.
- If using PHP’s
9. Deployment Considerations
When deploying to a live server:
- Use SMTP for Email Sending: PHP’s
mail()
function is unreliable on many hosting environments. Use SMTP via PHPMailer for consistent email delivery. - Secure Form Handling: Implement measures to prevent spam and abuse, such as CAPTCHA or rate limiting.
- Sanitize Inputs: Ensure all user inputs are sanitized to prevent SQL injection and XSS attacks.
- Use HTTPS: Ensure your website uses HTTPS for encrypted data transmission.
- Regular Backups: Implement regular backups of your database and files.
- Error Reporting: Disable detailed error messages in production to prevent information leakage.
// In production, set error reporting to minimal ini_set('display_errors', 0); ini_set('log_errors', 1);
- Update Dependencies: Keep PHP and all libraries updated to their latest versions to patch security vulnerabilities.
10. Enhancements and Best Practices
- Implement CSRF Protection: Use tokens to prevent Cross-Site Request Forgery attacks.
- Use Validation Libraries: Utilize PHP validation libraries for more robust input validation.
- Store Submissions in Database: Optionally, store contact form submissions in a database for record-keeping.
- Improve UI/UX: Enhance the user interface with better styling and responsiveness using frameworks like Bootstrap.
- Add Spam Protection: Integrate CAPTCHA services like Google reCAPTCHA to prevent spam submissions.
- Log Errors: Implement logging for form submission errors to facilitate troubleshooting.