X

How to Create Contact Form with PHPMailer to send mails


Every website have their own contact page to get feedback and messages from visitor, By the way it will help site owners to improve their website performance And Have idea about user experience. Here I am going to develop a simple contact form using HTML and send mails to administrative contacts with help of PHPMailer (A PHP Class).

First we need to create a contact form with help of HTML forms and design it with some CSS work based on your needs.You might save this file as contact.php

send-email-with-phpmailer

 

<?php 
if(isset($_GET['result']) && $_GET['result'] == 'success') {
      echo '<div class="success_msg" > Thank you for contacting us. We will get back to you soon. </div> ';
} ?>
<style>
     .success_msg {
          background-color: #fed;
          color: green;
          border: 1px solid green; 
     }
</style>
<form name="kv-contact-form" method="post" action="kv-contact-process.php">
<table width="450px">
</tr>
<tr>
<td valign="top">
<label for="first_name">First Name *</label>
</td>
<td valign="top">
<input type="text" name="first_name" maxlength="50" size="30">
</td>
</tr>

<tr>
<td valign="top"">
<label for="last_name">Last Name *</label>
</td>
<td valign="top">
<input type="text" name="last_name" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="email">Email Address *</label>
</td>
<td valign="top">
<input type="text" name="email" maxlength="80" size="30">
</td>

</tr>
<tr>
<td valign="top">
<label for="telephone">Telephone Number</label>
</td>
<td valign="top">
<input type="text" name="telephone" maxlength="30" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="subject">Subject</label>
</td>
<td valign="top">
<input type="text" name="subject" maxlength="30" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="comments">Comments *</label>
</td>
<td valign="top">
<textarea name="comments" maxlength="1000" cols="25" rows="6"></textarea>
</td>

</tr>
<tr>
<td colspan="2" style="text-align:center">
<!-- We are grateful to you for keeping this link in place. thank you. -->
<input type="submit" value="Submit"> ( <a href="http://kvcodes.com/2014/01/how-to-create-contact-form-with-phpmailer-to-send-mails/">Get Help from Kvcodes tut.</a> )
</td>
</tr>
</table>
</form>

Than style it with the help of CSS(Cascading Style Sheet).When User click on Submit button, it will send the data’s to `kv-contact-process.php`. Here we are going to handle the user entered data’s and send it to administrative email address at the same time we send a acknowledge to the respective user.

<?php
require_once("PHPMailerAutoload.php"); // this will include smtp and pop files.

if(isset($_POST['email'])) {

   $email_to = "info@yourdomain.com";

   function died($error) {// your error code can go here
        echo "We're sorry, but there's errors found with the form you submitted.<br /><br />";
        echo $error."<br /><br />";
        echo "Please go back and fix these errors.<br /><br />";
        die();
   }

   // validation expected data exists
   if(!isset($_POST['first_name']) ||!isset($_POST['last_name']) ||!isset($_POST['email']) ||!isset($_POST['telephone']) ||!isset($_POST['subject']) || !isset($_POST['comments'])) {
       died('We are sorry, but there appears to be a problem with the form you submitted.'); 
   }

   $first_name = $_POST['first_name']; // required
   $last_name = $_POST['last_name']; // required
   $email_from = $_POST['email']; // required
   $telephone = $_POST['telephone']; // not required
   $subject = $_POST['subject']; // required
   $comments = $_POST['comments']; // required

   $error_message = "";
   $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
   if(!preg_match($email_exp,$email_from)) {
       $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
   }
   $string_exp = "/^[A-Za-z .'-]+$/";
   if(!preg_match($string_exp,$first_name)) {
      $error_message .= 'The First Name you entered does not appear to be valid.<br />';
   }
   if(!preg_match($string_exp,$last_name)) {
       $error_message .= 'The Last Name you entered does not appear to be valid.<br />';
   }
   if(!preg_match($string_exp,$subject)) {
      $error_message .= 'The Last Name you entered does not appear to be valid.<br />';
   }
   if(strlen($comments) < 2) {
       $error_message .= 'The Comments you entered do not appear to be valid.<br />';
   }
   if(strlen($error_message) > 0) {
       died($error_message);
   }
   $email_message = "\n\n";

   $email_message .= "First Name: ".clean_string($first_name)."\n";
   $email_message .= "Last Name: ".clean_string($last_name)."\n";
   $email_message .= "Email: ".clean_string($email_from)."\n";
   $email_message .= "Telephone: ".clean_string($telephone)."\n";
   $email_message .= "Subject: ".clean_string($subject)."\n";
   $email_message .= "Comments: ".clean_string($comments)."\n";

   $mail = new PHPMailer();
   $mail->isSendmail();
   $mail->setFrom($email_from, $first_name.$last_name);
   $mail->addAddress($email_to, 'Kv Varadha);
   $mail->Subject = $subject;
   $mail->msgHTML(file_get_contents('path/to/file/attachment-file.extension'), dirname(__FILE__));

   if (!$mail->send()) { //send the message, check for errors
      echo "Mailer Error: " . died($error);
   } else {
       header('Location: contact.php?result=success'); 
   }
?>

<!-- place your own success html below -->

<?php
}
die();
?>

PHPMailer Class :

It have some extended features, just take look at here to use it effective way With CC, BCC and Reply-To . This is how you can design a contact form with phpmailer to send emails. If You have any queries and doubts drop your comment here.

commenter

About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, OpenCart Theme Development, PHP, HTML, CSS, jQuery, Bootstrap development and content SEO.

37 comments

  1. commenter

    Hi,
    i am a rookie web developer who is stuck with this phpmailer class. i would like to ask, if the user only put in his/her email address, then how isit able to send email out to the host? since phpmailer require the password of email, in order to authenticate the smtp.

    Sorry for taking up your time, and truly appreciate it if you can reply to me. Thank you.

    • commenter

      Without smtp you can send emails and dont need to authorize it.

      But it will take time to deliver emails.

      • commenter

        i tried to not put smtp but the email was not receive since sending it out 5-6 days ago. Is this normal? or do you have a tutorial regarding that? so i can relate to see what codes did i missed out.

        sorry for all the troubles.

  2. commenter

    Where is the article?
    I’d like to read it.

  3. commenter

    After buidling the mailform exactly as above, it does not work.
    by clicking the send button it only shows the php document inside the browser.
    besides that, shouldnt there be another document in here?
    the PHPMailerAutoload.php document?

    help please!
    thank you

    • commenter

      i think you didnt save your php file with ” .php ” extension. Else your server doesnot run php files. check your cpanel. if still it has problems than, it might be the php tag issue.

      your code must be begin with “< ?php " and finish with "?>“

  4. commenter

    Parse error: syntax error, unexpected end of file, expecting variable (T_VARIABLE) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN) in *********www\site1\phpmailer\mailform.php on line 98 is the error Im receiving after hitting submit

  5. commenter

    Fatal error: Call to undefined function clean_string() in D:\xampp\htdocs\mailer\kv-contact-process.php on line 56

  6. commenter

    Parse error: syntax error, unexpected ‘path’ (T_STRING) in /home/friendsa/public_html/process.php on line 71

    This is the error mesage thrown for me

  7. commenter

    hi
    I am not using any phpmailer for authorization and after hosting on free domain my code is working and mail send to gmail account but after purchased a domain same code create a error like this:
    “PHP Warning: mail(): SMTP server response: 530 Relaying not allowed – sender domain not local in D:\INETPUB\VHOSTS\raceitedu.com\httpdocs\process.php on line 115”
    what is the reason plz suggest me

  8. commenter

    I have the following PHP that I want to convert to using PHP Mailer with SMTP authentication. I have tried for hours and cannot figure it out. Any help would be greatly appreciated.

    Once the User completes the form it sends an email to the form owner, the form user, and updates a CVS file.

    <?php
    
    // Receiving variables
    @$Competitors_Name = addslashes($_POST['Competitors_Name']);
    @$Telephone_Number = addslashes($_POST['Telephone_Number']);
    @$Address = addslashes($_POST['Address']);
    @$City = addslashes($_POST['City']);
    @$State = addslashes($_POST['State']);
    @$Zip_Code = addslashes($_POST['Zip_Code']);
    @$Age = addslashes($_POST['Age']);
    @$DOB = addslashes($_POST['DOB']);
    @$Email = addslashes($_POST['Email']);
    @$Rank = addslashes($_POST['Rank']);
    @$Date = addslashes($_POST['Date']);
    @$Comments = addslashes($_POST['Comments']);
    
    // Validation
    
    //Sending Email to form owner
    # Email to Owner 
    $pfw_header = "From: $Email";
    $pfw_subject = "2015 TEST Owner Registration";
    $pfw_email_to = "webmaster@ikcweb.com";
    $pfw_message = "Competitors_Name: $Competitors_Name\n"
    . "Telephone_Number: $Telephone_Number\n"
    . "Address: $Address\n"
    . "City: $City\n"
    . "State: $State\n"
    . "Zip_Code: $Zip_Code\n"
    . "Age: $Age\n"
    . "DOB: $DOB\n"
    . "Email: $Email\n"
    . "Rank: $Rank\n"
    . "\n"
    . "Comments: $Comments\n";
    @mail($pfw_email_to, $pfw_subject ,$pfw_message ,$pfw_header ) ;
    //Sending auto respond Email to user
    # Email to Owner 
    $pfw_header = "From: webmaster@ikcweb.com";
    $pfw_subject = "2015 TEST User Registration";
    $pfw_email_to = "$Email";
    $pfw_message = "Thanks for registering the following Competitor; the 2015 IKC membership package will be mailed soon!\n"
    . "\n"
    . "$Competitors_Name\n"
    . "$Telephone_Number\n"
    . "$Address\n"
    . "$City, $State $Zip_Code\n"
    . "$Age ($DOB)\n"
    . "$Email\n"
    . "$Rank\n"
    . "\n"
    . "Comments: $Comments\n";
    @mail($pfw_email_to, $pfw_subject ,$pfw_message ,$pfw_header ) ;
    
    //saving record in a text file
    $pfw_file_name = "2015_IKC_Online_Reg.csv";
    $pfw_first_raw = "Competitors_Name,Telephone_Number,Address,City,State,Zip_Code,Age,DOB,Email,Rank,Date,Comments\r\n";
    $pfw_values = "$Competitors_Name,$Telephone_Number,$Address,$City,$State,$Zip_Code,$Age,$DOB,$Email,$Rank,$Date,$Comments\r\n";
    $pfw_is_first_row = false;
    if(!file_exists($pfw_file_name))
    {
     $pfw_is_first_row = true ;
    }
    if (!$pfw_handle = fopen($pfw_file_name, 'a+')) {
     die("Cannot open file ($pfw_file_name)");
     exit;
    }
    if ($pfw_is_first_row)
    {
      if (fwrite($pfw_handle, $pfw_first_raw ) === FALSE) {
      die("Cannot write to file ($pfw_filename)");
      exit;
      }
    }
    if (fwrite($pfw_handle, $pfw_values) === FALSE) {
      die("Cannot write to file ($pfw_filename)");
      exit;
    }
    fclose($pfw_handle);
    echo ''; 
    ?>
    • commenter

      You didn’t Configure SMTP here. Just tried to send mail. Also , where did you include the phpmailer class.

      • commenter

        Correct, I cannot figure it out and am asking for help.

        Thanks!

        • commenter

          I gave you the working codes. Please go through it. It will help you surely. Otherwise create a info.php file inside ur hosting with the following content

          < ?php 
          phpinfo (); 
          
          ? >
          

          If it returns the php informations your hosting supports php and check the php versions too. Than try to run your code.

  9. commenter

    When I press submit it just takes me to the php code. I have saved the file with the extension .php.
    Any idea how to get it to send?
    Cheers

  10. commenter

    When I copy the code and try to run it, I get a “Server Error 500” message. However, I run the code through a PHP code checker and get not syntax errors. Can someone explain any changes that had to be made before the code works?

  11. commenter

    You have 2 webpages:

    1. The html formular: kv-contact-process.php
    2. the PHP code action: PHPMailerAutoload.php

    Where are all the server information SMTP and all the other stuff needed to send and make a contact formular.

    Put out a new code that do the following.

    1. formular phpmailercontactform.php
    —————————————————-
    First Name *
    Last Name *
    Email Address *
    Telephone Number
    Subject *
    Comments *
    ————————–
    Fileupload buttom 1 or more files to send from webpage.
    Send buttom to webmaster.

    2. Collectdatafromformular.php.
    Check input fields are OK.
    Send message to webmaster.

    Redirect the person that send the message back to the webpage they they did come from.
    Whit at message that the e-mail is send correctly on the same page where the formular input is whit big text.

  12. commenter

    my code is not working

  13. commenter

    hello bro,
    i Recently checked your HRM Module and i am interested to buy it please tell me the price.
    I also want to integrate SMS with sale,purchase,payment,receipts,credit notes through api can u help me in this.
    I also want a little customization in sale and purchase forms
    please let me know if u can do this job for me
    waiting for quick response
    ReGards,
    TAYYAB FAYAYZ

  14. commenter

    hi friend, please i need your urgent response. I am using your php code for contact form. I am trying to style the php “success”page with my html and CSS but its not working. I cant even style the background color….absolutely not working. On my code editor, the color of all my code is a dull ash color all through, so its obviously not working

    • commenter

      Can you see the success Message after the form submission.?.

      It might be the issue with css. You can directly open. The url on browser to take effect. May be the stylesheet cached for better bandwidth consumption. So use Developer Tools on your chrome and see the element changes and check the custom style applied it or not.

  15. commenter

    hi friend, please i need your urgent response. I am using your php code for contact form. I am trying to style the php “success”page with my html and CSS but its not working. I cant even style the background color….absolutely not working. On my code editor, the color of all my code is a dull ash color all through, so its obviously not working. I use codelobster editor

  16. commenter

    THIS IS HOW I APPLIED your PhP to HTML AND CSS ….but its not working…..This is my site http://www.cubedwebs.com

    <?php
    require_once("PHPMailerAutoload.php"); // this will include smtp and pop files.

    if(isset($_POST['email'])) {

    $email_to = "henry@cubedwebs.com";

    function died($error) {
    // your error code can go here
    echo "We're sorry, but there's errors found with the form you submitted.”;
    echo $error.””;
    echo “Please go back and fix these errors.”;
    die();
    }

    // validation expected data exists
    if(!isset($_POST[‘first_name’]) ||
    !isset($_POST[‘last_name’]) ||
    !isset($_POST[’email’]) ||
    !isset($_POST[‘subject’]) ||
    !isset($_POST[‘message’])) {
    died(‘We are sorry, but there appears to be a problem with the form you submitted.’);
    }

    $first_name = $_POST[‘first_name’]; // required
    $last_name = $_POST[‘last_name’]; // required
    $email_from = $_POST[’email’]; // required
    $subject = $_POST[‘subject’]; // required
    $comments = $_POST[‘message’]; // required

    $error_message = “”;
    $email_exp = ‘/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/’;
    if(!preg_match($email_exp,$email_from)) {
    $error_message .= ‘The Email Address you entered does not appear to be valid.’;
    }
    $string_exp = “/^[A-Za-z .’-]+$/”;
    if(!preg_match($string_exp,$first_name)) {
    $error_message .= ‘The First Name you entered does not appear to be valid.’;
    }
    if(!preg_match($string_exp,$last_name)) {
    $error_message .= ‘The Last Name you entered does not appear to be valid.’;
    }
    if(!preg_match($string_exp,$subject)) {
    $error_message .= ‘The Last Name you entered does not appear to be valid.’;
    }
    if(strlen($message) < 2) {
    $error_message .= 'The message you entered do not appear to be valid.’;
    }
    if(strlen($error_message) > 0) {
    died($error_message);
    }
    $email_message = “\n\n”;

    $email_message .= “First Name: “.clean_string($first_name).”\n”;
    $email_message .= “Last Name: “.clean_string($last_name).”\n”;
    $email_message .= “Email: “.clean_string($email_from).”\n”;
    $email_message .= “Subject: “.clean_string($subject).”\n”;
    $email_message .= “message: “.clean_string($message).”\n”;

    $mail = new PHPMailer();

    $mail->isSendmail();

    $mail->setFrom($email_from, $first_name.$last_name);

    $mail->addAddress($email_to, ‘Henry Ononiwu);
    $mail->Subject = $subject;
    $mail->msgHTML(file_get_contents(‘/home/cubedweb/public_html/php/contact.php’), dirname(__FILE__));

    //send the message, check for errors
    if (!$mail->send()) {
    echo “Mailer Error: ” . died($error);
    } else {
    echo ”

    Thank you for contacting us. We will be in touch with you very soon.\n
    \n
    By,\n
    Henry Ononiwu.\n”;
    }
    ?>


    Cubed Webs

    body{
    background-color:#575652;
    color:#22222;
    }



    Thank you for contacting us. We will be in touch with you very soon.!

    • commenter

      Your code should be like this.

      else {
              echo ”  < div class='success'  > 
              Thank you for contacting us. We will be in touch with you very soon.\n
              By,\n
               Henry Ononiwu.\n   < / div >”;
             }
           ?>
            
      
  17. commenter


    Cubed Webs

    body{
    background-color:#575652;
    color:#22222;
    }



    Thank you for contacting us. We will be in touch with you very soon.!

  18. commenter

    hi, how do i add a page redirect to you form submission code? Please am totally new to php and just need to get my form working. I will be happy if you can send the complete code with the page redirect to html and send it to my email

Comment Below

Your email address will not be published. Required fields are marked *

*

Current ye@r *

Menu

Sidebar

Subscribe E-mail Updates

Subscribe to our email newsletter.

 

Advertisement

Category Posts