Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 41

PHP Contact Form with Email

In this lesson: Make a working PHP contact form that sends email — validation, spam protection and SMTP via PHPMailer.

What we are building

A contact form lets visitors send you a message from your website. It has two pieces: an HTML form the user fills in, and a PHP file that validates the input and sends it to your email. Handling it safely and reliably is a very common task.

💡 The built-in mail() works for demos, but for real sites use PHPMailer with SMTP so messages actually arrive.

The contact form

<form method="post" action="contact.php">
  <input type="text"  name="name"    placeholder="Your name">
  <input type="email" name="email"   placeholder="Your email">
  <textarea name="message" placeholder="Message"></textarea>
  <button type="submit">Send</button>
</form>

The form posts to contact.php. Each field's name is the key PHP reads. Keep the fields simple and clearly labelled.

Validating input

Never email raw input. Check it first.

<?php
  $name    = trim($_POST["name"] ?? "");
  $email   = trim($_POST["email"] ?? "");
  $message = trim($_POST["message"] ?? "");

  $errors = [];
  if ($name === "") $errors[] = "Name required";
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Valid email required";
  if ($message === "") $errors[] = "Message required";
?>

We trim each field, require a name and message, and validate the email with filter_var. Only send the mail if $errors is empty.

Sending the email

<?php
  if (empty($errors)) {
      $to      = "you@yoursite.com";
      $subject = "New contact from $name";
      $body    = "From: $name ($email)\n\n$message";
      $headers = "From: no-reply@yoursite.com\r\n";
      $headers .= "Reply-To: $email\r\n";

      if (mail($to, $subject, $body, $headers)) {
          echo "Message sent";
      }
  }
?>
Message sent

Notice From is your own address and the visitor's email goes in Reply-To — so you can reply, without triggering spoofing filters.

Why use PHPMailer

The plain mail() function often lands in spam or fails silently. For real sites, use PHPMailer, which sends through SMTP with your email account's login, so messages are properly authenticated and reach the inbox.

<?php
  // simplified PHPMailer idea:
  $mail->isSMTP();
  $mail->Host = "smtp.gmail.com";
  $mail->SMTPAuth = true;
  $mail->Username = "you@gmail.com";
  $mail->Password = "app-password";
  $mail->send();
?>

PHPMailer handles authentication, encoding and attachments correctly — the reliable choice for production.

Common mistakes

  • Emailing raw input. Always validate; check email with filter_var.
  • Putting the visitor email in From. Use your address in From, visitor's in Reply-To.
  • Relying on mail() in production. Use PHPMailer + SMTP for reliable delivery.
  • No spam protection. Add a honeypot or CAPTCHA to stop bots.

Summary

  • A contact form = an HTML form plus a PHP handler that emails you.
  • Validate every field and check the email with filter_var.
  • Put your address in From, the visitor's in Reply-To.
  • Use PHPMailer with SMTP for reliable delivery, not plain mail().
  • Add spam protection like a honeypot or CAPTCHA.

Next, validate input thoroughly with form validation, or add a check with PHP CAPTCHA.

Frequently Asked Questions

How does a PHP contact form send email?
The form posts the name, email and message to a PHP file. The PHP validates the input and then sends an email — either with the built-in mail() function or, more reliably, with a library like PHPMailer using SMTP.
Why does PHP mail() often not deliver?
The built-in mail() function depends on the server being configured to send mail, and its messages often land in spam or are blocked. For real sites, PHPMailer with proper SMTP settings is far more reliable.
How do I stop spam in a contact form?
Validate all fields, check the email with filter_var, and add a simple check like a honeypot field or a CAPTCHA. Never email raw, unchecked input, and escape anything you display back.
Should I put the visitor email in the From header?
No. Use your own verified address in From and put the visitor's email in Reply-To. Sending as the visitor's address often gets blocked as spoofing.
What is PHPMailer?
PHPMailer is a popular library that sends email through SMTP with proper authentication. It handles headers, attachments and encoding correctly, so your messages actually reach the inbox — much better than plain mail().
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicImage Upload Script Your progress: 41 / 50 (82%) · Lesson 42 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free