Last Updated on April 5, 2022 by Roshan Parihar
In this post, learn how to create contact form in PHP and send form data in email. The short answer is to use the PHPMailer function to send emails in PHP.
Every website needs a contact form to receive user’s input data to their email id. Contact forms are the best option to connect with your audience and
You have to first create a complete contact form with fields like name, email, subject, and message. When the user submits the form, it should be first validated to check the fields are not empty and the email format is correct.
After the form gets validated and the user enters valid data, you have to use the PHP code with PHPMailer to send form data in email. The best option to send emails is to use the Gmail SMTP to confirm sending of emails.
In this post, you will learn the step-by-step process of how to create a contact form and email form data. So, let’s get started.
How to Create Contact Form in PHP and Send Email
Let’s start with creating a contact form in PHP with standard form fields.
Step 1: Create a Contact Form in PHP
Here are the form fields including name, email, subject, and message with a submit button. Also, add action
and method
attribute. The action
contains the value as the location PHP page where you have placed your PHP codes. The method
attribute contains the value ‘POST’ as you have to post form data on submission.
1 2 3 4 5 6 7 |
<form action="post.php" method="POST"> <input type="text" name="name" class="name form-control" placeholder="Enter name"> <input type="text" name="subject" class="subject form-control" placeholder="Enter subject"> <input type="email" name="email" class="email form-control" placeholder="Enter email"> <textarea name="message" class="message form-control" placeholder="Enter your message" rows="3"></textarea> <input name="submit" type="submit" value="Submit" class="submit btn btn-primary"> </form> |
Step 2: Validate Your Contact Form Using jQuery
After you have created your form, you have to validate your form data to collect valid input from users. You can use jQuery for form validation as given below. It first checks whether the form fields are empty or not. If the form fields are empty, it will not allow users to proceed.
It also checks the email id input if its format is correctly entered by the users or not. If the email format is not correct, it will also do not allow users to submit the form.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(document).ready(function(){ $(".submit").click(function (event){ //get value of form fields var name = $(".name").val(); var email = $(".email").val(); var subject = $(".subject").val(); var message = $(".message").val(); //Function to email address validation function validateEmail(email) { var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; return emailReg.test( email ); } //Check if email format is correct if( !validateEmail(email)) { alert("Enter a valid email address"); $("form").find("input[type=email]").css("border","1px solid orange"); //Highlight invalid email form field setTimeout(function() { $("form").find("input[type=email]").css("border","1px solid #ced4da"); }, 1000); return false; } //check if fields are empty if (name == '' || email == '' || subject == '' || message == ''){ $('.success').fadeOut(200).hide(); $('.error').fadeOut(200).show(); } event.preventDefault(); }); }); </script> |
Don’t forget to match the class of the form fields with the above variable and the submit button. After form validation, you can proceed further to collect user’s input data and send emails using PHP.
Step 3: Email Form Data to the Recipient Using PHPMailer
First of all, download the PHPMailer file on the base location where you have placed your PHP code file.
Now, you can create a PHP code to collect form data and email them to the receiver. First, you have to check if the form submitted uses the PHP isset() function as shown below.
If the form is submitted, its data are collected in a separate variable. After that, it uses the SMTP and PHPMailer to send emails as shown in the PHP code below:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<?php if(isset($_POST["submit"])){ //Get form data in variables $name = $_POST['name']; $email = $_POST['email']; $subject = $_POST['subject']; $message = $_POST['message']; //Use PHPmailer require "phpmailer/PHPMailerAutoload.php"; $mail = new PHPMailer; //Mailbody to send in email $mailbody = "The details submitted on contact form are:-<br><br><b>Name:</b> ".$name . "<br> <b>Email:</b> ".$email . "<br> <b>Subject:</b> " . $_POST['subject'] . "<br> <b>Message:</b> " . $_POST['message']; //Sender email address $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $sender; // SMTP username $mail->Password = 'gmailpassword';// Gmail SMTP password $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 587; // TCP port to connect to $mail->setFrom($sender, 'Sendername'); //$mail->addAddress('[email protected]'); //add more recipient (optional) //$mail->addReplyTo('[email protected]', 'replytoname'); //$mail->addCC('[email protected]'); //$mail->addBCC('[email protected]'); $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Contact Form '.'"'.$subject.'"'; $mail->Body = $mailbody; //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; //Email your contact form data using Gmail SMTP with PHPMailer if(!$mail->send()){ echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; }else{ echo 'Message has been sent successfully'; } } ?> |
You have to place the above PHP code inside a separate PHP file. After that, add the attribute action="post.php"
inside the <form>
tag. The ‘post.php’ file contains the above PHP code to execute on form submission.
Now, your contact form is ready to get submitted and send emails to the recipients. You can add as many recipients as you want.
You May Also Like to Read
- Ajax Image Upload Using PHP, jQuery With Image Preview
- How to Convert or Change Date Format to Another in PHP
- How to Use CSS in PHP Echo to Add Style (3 Easy Ways)
I hope you like this post on how to create a contact form in PHP and send emails.