Main Street Docs

Contact Form Code: How to Build One

Updated November 28, 2026

Blank template:PDFWordSample wording, a generic template. Not legal advice; check what applies to you.

The simplest contact form code is an HTML <form> element with action and method attributes, plus input fields and a submit button. However, that alone does nothing—you need a server-side script (like PHP, Node.js, or a form backend service) to receive and process the submitted data, or the form will just reload the page.

What a Contact Form Actually Does

A contact form is a user interface that collects visitor input and sends it to a destination you control, usually an email inbox or a database. The HTML defines the visible structure (fields, labels, buttons). The method attribute tells the browser how to send the data—GET appends it to the URL, POST sends it in the request body, which is standard for forms because it keeps data out of the URL and can handle larger payloads. The action attribute points to the URL of the server-side script that will process the submission.

Without a backend, the form is just a static shell. When a user clicks submit, the browser sends the data to the action URL. If that URL doesn’t exist or doesn’t handle the request, the user sees an error or a blank page. That’s why most tutorials pair HTML with a language like PHP, or recommend a third-party service that provides a ready-made endpoint.

Basic HTML Structure

Here is a minimal, functional HTML form (the backend is assumed to be at /submit-form.php):

<form action="/submit-form.php" method="POST">
  <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="message">Message</label>
  <textarea id="message" name="message" rows="5" required></textarea>

  <button type="submit">Send</button>
</form>

Key points:

  • name attributes are essential—they become the keys in the submitted data (e.g., $_POST['name'] in PHP).
  • type="email" triggers browser-side validation for email format.
  • required prevents submission if the field is empty (but always validate on the server too).
  • The label elements improve accessibility—clicking a label focuses its input.

Server-Side Processing (PHP Example)

Here’s a simple PHP script that sends the form data to an email address. It uses the built-in mail() function, which requires a configured mail server (often available on shared hosting).

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $name = strip_tags($_POST["name"] ?? "");
  $email = filter_var($_POST["email"] ?? "", FILTER_VALIDATE_EMAIL);
  $message = strip_tags($_POST["message"] ?? "");

  if ($name && $email && $message) {
    $to = "you@example.com";
    $subject = "New message from $name";
    $body = "Name: $name\nEmail: $email\nMessage:\n$message";
    $headers = "From: $email";

    if (mail($to, $subject, $body, $headers)) {
      echo "Thank you, your message has been sent.";
    } else {
      echo "Sorry, something went wrong. Please try again.";
    }
  } else {
    echo "Please fill in all fields correctly.";
  }
}
?>

This code sanitizes input with strip_tags() and validates the email with filter_var(). It’s a basic example—production forms should also include CSRF protection, rate limiting, and better error handling.

How to Choose a Method or Service

You have three main paths:

  • Self-hosted script (PHP, Python, Node.js): Full control, but requires server access and maintenance. Good for developers comfortable with backend code.
  • Form backend services (e.g., Formspree, Getform, Basin): You point the form’s action to their URL, and they forward submissions to your email. No server code needed, but you rely on a third party and may hit free-tier limits.
  • Static site + API: Use a service like Netlify Forms or a serverless function to handle submissions. Works well with Jekyll, Hugo, or plain HTML sites.

For a simple personal site, a service is often the fastest. For a business with high volume or custom logic, a self-hosted script gives more control.

Common Problems and How to Avoid Them

  • Emails going to spam: Use a reputable mail service (like SendGrid or Amazon SES) instead of PHP’s mail()—it lacks authentication and often gets flagged.
  • Spam submissions: Add a honeypot field (hidden input that bots fill) and/or a CAPTCHA (like reCAPTCHA). Simple spam filters can also check for suspicious patterns.
  • Page reload on submit: Without JavaScript, the form reloads the page. To avoid that, use AJAX to submit the form in the background and show a success message.
  • Missing validation: Always validate on the server—never trust client-side validation alone. An attacker can bypass HTML5 checks.
  • Broken action URL: Ensure the path is correct and the script is executable. A 404 error means the form can’t submit.

Security and Privacy Considerations

Contact forms collect personal data (name, email, message). If you operate in the EU, GDPR requires you to inform users how their data is used and to obtain consent if you store it. Always use HTTPS to encrypt the data in transit. Never log passwords or sensitive information from form fields. For email delivery, use a service that supports SPF and DKIM to reduce spam flags. If you store submissions in a database, sanitize inputs and use prepared statements to prevent SQL injection.

Template

Below is a blank contact form template. Copy it and replace the action URL with your backend endpoint.

Field Type Name Required
Name text name Yes
Email email email Yes
Subject text subject No
Message textarea message Yes

Sample (fictional): John Doe, johndoe@example.com, Subject: “Question about your services”, Message: “Hi, I’d like to know more about your pricing.”

Frequently Asked Questions

Do I need JavaScript to make a contact form?

No. HTML forms work without JavaScript—the browser handles submission. JavaScript is only needed for client-side validation (which you should also do server-side), AJAX submission to avoid page reloads, or to integrate with certain APIs.

What is a honeypot field?

A honeypot is a hidden input field that human users won’t see or fill, but bots often do. If the field is filled on submission, the server discards the message, effectively blocking many spam bots. It’s a simple, user-friendly alternative to CAPTCHA.

How do I prevent spam without annoying users?

Use a combination of a honeypot, rate limiting (e.g., max 2 submissions per minute per IP), and a simple math question (e.g., “What is 3+4?”). These are less intrusive than a CAPTCHA and often enough for low-traffic sites.

Can I use a contact form without a backend?

Yes, you can use a form backend service. You sign up, get a unique URL, and set that as the action. The service handles the backend and forwards submissions to your email. Some services offer free tiers with limits.

Why are my form emails going to spam?

Most likely because your server’s email lacks authentication (SPF/DKIM). PHP’s mail() often sends from the server’s default address, which can be flagged. Using a transactional email service (like SendGrid or Mailgun) with proper authentication dramatically improves deliverability.

Is it safe to use mail() in PHP?

It’s not recommended for production. The function is simple but lacks support for authentication, which leads to spam folder issues. Also, it’s vulnerable to header injection if you don’t sanitize the $headers variable. Use a well-maintained library like PHPMailer or a third-party service instead.

Related