Setting up a basic contact us form for your site

Download files of this tutorial

github starting version

github final version

Step 1: Setup Your Email

http://www.outsource-online.net/blog/2022/06/07/setting-up-an-email-for-your-domain-with-cpanel/

Optional Step

Run the below createFiles.bat to create required files

@echo off
setlocal
:PROMPT
set GIT_BRANCH_NAME=bob
set /p functionalityName="Enter functionality Name: or 'q' to quit "
echo "Entered functionality Name was " %functionalityName%
set quitbat=true
IF not "%functionalityName%" == "q" IF not "%functionalityName%" ==  "Q" set quitbat=false
if "%quitbat%" == "true" goto END
:NOTEND
rem echo "Inside :NOTEND Entered Value was " %ANYKEY%
echo html >> %functionalityName%.html
echo PHP >> %functionalityName%.php
echo PHP >> %functionalityName%Validate.php
echo PHP >> %functionalityName%Config.php
echo PHP >> %functionalityName%Execute.php
mkdir emailTemplates
echo html >> emailTemplates/emailTemplate.html

set /p ANYKEY="Successfully created files for %functionalityName%, Press any key to continue: "
:END
endlocal

Step 2: Create a blank page to hold contactus form.

Below is an example with materialize framework. You may use your chosen framework or even vanilla JS.
Advantage of using frameworks like materialize or bootstrap is that you will get a lot of free code for validation, responsiveness etc

contactUs.html

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Contact Us with Material Design Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

    <!--  Material I cons from Google Fonts. -->
   <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body>

<div class="container">
  <h1>Contact Us with Material Design</h1>
  <p>This is some text.</p>
</div>
    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

</body>
</html> 

Step 3 : Create a contact Us form.

<!-- contact form -->
  <section class="section container scrollspy" id="contact">
    <div class="row">
          <div id="loader"></div>
      <div class="col s12 l5">
        <h2 class="indigo-text text-darken-4">Get in Touch</h2>
        <p>Share the details of your project – like scope, </p>
        <p>Timeframes, or business challenges you'd like to solve. </p>
        <p>Our team will carefully study them and then we’ll figure out the next move together.</p>
        <p>No matter how complex, we will find the best solution and complete it within a fixed time.</p>
      </div>
      <div  class="col s12 l5 offset-l2  ">

            <form name="contactForm" id="contactForm" action="contactUs.php" method="post" enctype="multipart/form-data">
              <div class="input-field">
                <i class="material-icons prefix">email</i>
                <input type="email" name="email" id="email" required>
                <label for="email">Your Email</label>
              </div>
              <div class="input-field">
                <i class="material-icons prefix">message</i>
                <textarea name="message" id="message" class="materialize-textarea" cols="20" rows="20"  required></textarea>
                <label for="message">Your Message</label>
              </div>
              <div class="input-field">
                <i class="material-icons prefix">date_range</i>
                <input name="date" type="text" id="date" class="datepicker">
                <label for="date">Choose a date you would like to chat...</label>
              </div>
              <div class="input-field">
                <p>Services required:</p>
                <p>
                  <label>
                    <input name="contactFor[]" value="Mobile App Development" type="checkbox">
                    <span>Mobile App Development</span>
                  </label>
                </p>
                <p>
                  <label>
                    <input name="contactFor[]" value="Web Solutions" type="checkbox">
                    <span>Web Solutions</span>
                  </label>
                </p>

              </div>
              <div class="input-field center">
                <button type="submit" id="contactSubmit"  class="btn waves-effect waves-light">Submit</button>
              </div>
            </form>

      </div>
    </div>
  </section>

Step 4: Download PHP Mailer

https://github.com/PHPMailer/PHPMailer
Could be downloaded in 2 ways

  1. Direct download
  2. Using composer . This is easier for me, about composer.
composer require phpmailer/phpmailer

Step 5: Create PHP Script to handle Contact Use Form submission

to make it simple, I prefer to do it with 4 scripts, this is in addition to PHPMailer files downloaded via composer above

  1. contactUs.php : main script to which form is submitted
  2. contactUsValidate.php : where the posted variables are validated
  3. contactUsConfig.php : where the different variables to send email are set
  4. contactUsExecute.php : handles the functionality of sending mail with PHPMailer ,based on config set in mailConfig.php and variables from contact us form
    AND
    5.In addition to the above files, we need an email template file emailTemplates/emailTemplate.html

contactUs.php

<?php 
//validate POST vars 
require_once('contactUsValidate.php');
require 'vendor/autoload.php'; // include vendor/autoload.php to load PHPMailer Class
require_once('contactUsConfig.php');
require_once('contactUsExecute.php');
?>

contactUsValidate.php

<?php
/**************************GET THE SUBMITTED VARIABLES AND VALIDATE******************************/
function valid_email($str) {
        return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
$senderEmail = isset($_POST['email'])?$_POST['email']:"";
$postedMessage = isset($_POST['message'])?$_POST['message']:"";
$dateSelected = isset($_POST['date'])?$_POST['date']:"";
if(trim($senderEmail) == "" || !valid_email($senderEmail))die('{"status":"Error","mesage":"You should enter a valid email address"}');
if(trim($postedMessage) == "")die('{"status":"Error","mesage":"Message should not be empty"}');

$messageBody = "";
$messageBody .= "Sender Email : ".$senderEmail."<br/>";
$messageBody .= "Message : ".$postedMessage."<br/>";
$messageBody .= "Date Selected : ".$dateSelected."<br/>";
if(isset($_POST['contactFor']) && count($_POST['contactFor'])>0)
$messageBody .= "Contacting for : ".join(",",$_POST['contactFor'])."<br/>";
if(isset($_FILES['fileToUpload']) && isset($_FILES['fileToUpload']['name']))
{
    $messageBody .= "Attachment : ".$_FILES['fileToUpload']['name']."<br/>";
}//if(isset($_POST['contactFor']) && count($_POST['contactFor'])>0)
/**************************GET THE SUBMITTED VARIABLES AND VALIDATE ENDS HERE******************************/
?>

contactUsConfig.php

<?php
$OSOL_PHPMailer_CONFIG = array(
                            'username' => 'username of email',
                            'password' => 'password of email', // app password if it is gmail
                            'smtpHost' => 'smtp server url',
                            'smtpPort' => 587,// check with the host, ususally it is 587
                            'SMTPSecure' => 'TLS',// PHPMailer::ENCRYPTION_STARTTLS OR PHPMailer::ENCRYPTION_STARTSMTPS
                            'fromEmail' => 'yourFromEmail@domain.com',
                            'fromName' => 'your from name',
                            'addAddressEmail' => 'yourAddAddressEmail@domain.com',
                            'addAddressName' => 'your Add Address name',
                            'Subject' => 'your subject for contact us mail submission',
                            'htmlContentDir' => __DIR__."/emailTemplates",// folder where hmtl template is saved
                            );                  
?>

contactUsExecute.php

<?php
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;   
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
$mail->SMTPDebug = SMTP::DEBUG_OFF;// there are other options like SMTP::DEBUG_SERVER;
//Set the hostname of the mail server$class = new ReflectionClass('PHPMailer\PHPMailer\PHPMailer');
$mail->Host = $OSOL_PHPMailer_CONFIG['smtpHost'];
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port =  $OSOL_PHPMailer_CONFIG['smtpPort'];//465;//587;
$smtpSecureConstant = 'ENCRYPTION_START' . $OSOL_PHPMailer_CONFIG['SMTPSecure'];
//use reflection class to get constant with variable
$class = new ReflectionClass('PHPMailer\PHPMailer\PHPMailer');
$SMTPSecure=$class->getConstant($smtpSecureConstant);
//echo $SMTPSecure."<br/>";
$mail->SMTPSecure = $SMTPSecure;//PHPMailer::$smtpSecureConstant;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = $OSOL_PHPMailer_CONFIG['username'];
//Password to use for SMTP authentication
$mail->Password = $OSOL_PHPMailer_CONFIG['password'];
$mail->setFrom($OSOL_PHPMailer_CONFIG['fromEmail'], $OSOL_PHPMailer_CONFIG['fromName']);
//Set an alternative reply-to address
$mail->addReplyTo($senderEmail );//, 'Sender name if you know it');
$mail->addAddress($OSOL_PHPMailer_CONFIG['addAddressEmail'], $OSOL_PHPMailer_CONFIG['addAddressName']);
//Set the subject line
$mail->Subject = $OSOL_PHPMailer_CONFIG['Subject'];
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$htmlContentDir = $OSOL_PHPMailer_CONFIG['htmlContentDir'];
$mail->msgHTML(str_replace("__MAIL_CONTENT__",$messageBody,file_get_contents($htmlContentDir.'/emailTemplate.html')),$htmlContentDir );
//Replace the plain text body with one created manually
$mail->AltBody = ($messageBody.'This is a plain-text message body'). str_replace("<br />","\r\n",$messageBody);
if (!$mail->send()) {
    //echo 'Mailer Error: '. $mail->ErrorInfo;
    die("{\"status\":\"error\",\"message\":\"".addslashes($mail->ErrorInfo)."\"}");
} else {
    die('{"status":"Success"}');
}
?>

emailTemplates/emailTemplate.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <title>Simple Contact Us form</title>
</head>
<body>
<div style="width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 11px;">
  <h1>This is a mail sent with simple contact us form by OSOL Solutions</h1>

  <p>This example uses <strong>HTML</strong>.</p>
  <p>__MAIL_CONTENT__</p>
  <p>ISO-8859-1 text: éèîüçÅñæß</p>
</div>
</body>
</html>

Step 6 : Test your contactUs.html

To do

The above codes will just create a crude contact us form. I explained it in simple terms. But in real sites you need few more features

1. Use OOP to handle functionalities for sending mail via PHPMailer

2. Adding JS Validation code and AJAX submit

3. Adding Captcha

4. Adding File Upload feature

5. Implementing Captcha Without Cookie

Each of these will be explained in the coming tutorials