Contact Form with Email Sending in PHP

The Contact Form is an essential element for almost every website. The contact us form allows visitors to communicate with the site owner from the website. Using the contact us form, visitors can easily submit their queries, views, opinions, and suggestions to the site administrator about the website, service, or product. Also, the submitted information can be sent to the site owner or administrator via email.

Contact form helps you receive queries from visitors and provide a quick response to them. The thought of a contact form is very simple; the user is able to send their query via email to the respective organization. In this tutorial, we’ll show you how to create a simple contact form with PHP and integrate it into your website. Using our PHP contact form script, you’ll be able to add a contact us form to your website within 5 minutes. The contact form not only submits, but also sends an email to you on every form submission using PHP.

PHP Contact Form with Email

In this example script, we will build a contact form with email functionality using PHP. For better understanding, we will divide the PHP contact form script into two parts: the HTML form and the submission code. You can place this code together on the web page where you want to display the contact us form widget.

Contact Form HTML:
Create an HTML form with some input elements (Name, Email, Subject, and Message).

  • Add an input type="submit" element to provide a submit button in the form.

At the top of the contact form, display the form submission status message with PHP.

  • If the form submission fails, use PHP to retrieve the submitted inputs from the $_POST variable and fill them into the input fields.
<!-- Status message -->
<?php if ($success): ?> 
    <div class="success-message"><?php echo $success?></div>
<?php else: ?>
    <?php
    $allErrors 
array_filter($errors);
    if (!empty(
$allErrors)) {
        echo 
'<div class="error-message">';
        foreach (
$errors as $key => $msg) {
            if (
$msg && $key !== 'general') {
                echo 
htmlspecialchars($msg) . "<br>";
            }
        }
        if (!empty(
$errors['general'])) {
            echo 
htmlspecialchars($errors['general']) . "<br>";
        }
        echo 
'</div>';
    }
    
?>
<?php 
endif; ?> <!-- Form fields --> <form method="post" action=""> <div class="form-group"> <label for="name">Name</label> <input type="text" name="name" required placeholder="Your Name" value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" name="email" required placeholder="ex: your@email.com" value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>"> </div> <div class="form-group"> <label for="subject">Subject</label> <input type="text" name="subject" required placeholder="Subject of your request" value="<?php echo htmlspecialchars($_POST['subject'] ?? ''); ?>"> </div> <div class="form-group"> <label for="message">Message</label> <textarea name="message" required placeholder="Type your message here"><?php echo htmlspecialchars($_POST['message'] ?? ''); ?></textarea> </div> <input type="submit" name="submit" class="submit-btn" value="Send Message"> </form>

Contact Form Submission with PHP:
The following PHP code snippet handles the form submission process and email sending functionality.

  • Retrieve the input values of form fields using the PHP $_POST variable, and sanitize inputs.
  • Validate input fields and make sure they are not empty. Also, validate the email address using the PHP FILTER_VALIDATE_EMAIL filter.
  • Send an email with input form data using the PHP mail() function.

Note: Place this code at the top of the web page before the HTML form code.

<?php 
$success 
'';
$errors = [];

// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    
// Sanitize inputs
    
$name trim($_POST['name'] ?? '');
    
$email trim($_POST['email'] ?? '');
    
$subject trim($_POST['subject'] ?? '');
    
$message trim($_POST['message'] ?? '');

    
// Validate inputs
    
if (empty($name)) {
        
$errors['name'] = "Please enter your name.";
    }
    if (empty(
$email)) {
        
$errors['email'] = "Please enter your email address.";
    } elseif (!
filter_var($emailFILTER_VALIDATE_EMAIL)) {
        
$errors['email'] = "Please enter a valid email address.";
    }
    if (empty(
$subject)) {
        
$errors['subject'] = "Please enter a subject.";
    }
    if (empty(
$message)) {
        
$errors['message'] = "Please enter your message.";
    }

    if (empty(
$errors)) {
        
// Prepare email
        
$to "admin@example.com"// Change to your admin email
        
$email_subject "Contact Form: " htmlspecialchars($subject);

        
$email_body '
        <html>
        <head>
          <style>
            body { font-family: Arial, sans-serif; background: #f9f9f9; }
            .email-container { background: #fff; padding: 24px; border-radius: 8px; box-shadow: 0 2px 8px #eee; }
            .header { font-size: 17px; color: #333; margin-bottom: 16px; }
            .info { margin-bottom: 12px; }
            .label { font-weight: bold; color: #555; }
            .message { background: #f1f1f1; padding: 12px; border-radius: 4px; }
          </style>
        </head>
        <body>
          <div class="email-container">
            <div class="header">New Contact Form Submission</div>
            <div class="info"><span class="label">Name:</span> ' 
htmlspecialchars($name) . '</div>
            <div class="info"><span class="label">Email:</span> ' 
htmlspecialchars($email) . '</div>
            <div class="info"><span class="label">Subject:</span> ' 
htmlspecialchars($subject) . '</div>
            <div class="label">Message:</div>
            <div class="message">' 
nl2br(htmlspecialchars($message)) . '</div>
          </div>
        </body>
        </html>'
;

        
$headers  "MIME-Version: 1.0\r\n";
        
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
        
$headers .= "From: " htmlspecialchars($name) . " <" $email ">\r\n";
        
$headers .= "Reply-To: " $email "\r\n";

        
// Send email
        
if (@mail($to$email_subject$email_body$headers)) {
            
$success "Thank you for contacting us! Your message has been sent.";

            
// Clear form fields after successful submission
            
$_POST = [];
        } else {
            
$errors['general'] = "Sorry, there was a problem sending your message. Please try again later.";
        }
    }
}
?>

Note: Make sure to change the value of the $to variable to your admin email address where you want to receive the contact form submissions.

Conclusion

The code snippet mentioned above can be used as a ready-to-use script to add a contact form with email functionality to the website using PHP. We have used a professional UI in this contact form so that it fits with all types of webpage templates. But if you want, you can easily customize the functionality of this contact form to suit your needs. As an advanced feature, you can add captcha functionality to the contact form to protect against spam submissions – PHP Contact Form with Google reCAPTCHA.

Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request

16 Comments

  1. Krat Ohm Said...
  2. Vgo Said...
  3. Abiodun Ilesanmi Said...
  4. Abiodun Ilesanmi Said...
  5. Nick Said...
  6. Purushotam Said...
  7. Lyada Emmanuel Said...
  8. Lin Said...
    • CodexWorld Said...
  9. Lin Said...
    • CodexWorld Said...
  10. Željka Said...
    • CodexWorld Said...
  11. Nuffsaid Said...
    • CodexWorld Said...

Leave a reply

construction Need this implemented in your project? Request Implementation Help → keyboard_double_arrow_up