Last Updated on February 9, 2023 by Roshan Parihar
In this tutorial, learn how to create a PHP contact form with attachment and send data via email. It can help you know the query of your customers visually.
If you are running a business online, you need a contact form that collects customers’ queries. You can collect attachments like jpg, png, pdf, and doc along with text content from it.
Looking to create contact forms with attachments without coding required? Create beautiful-looking contact forms with JotForm.
Sometimes text messages of customers are not enough to know the exact queries. You need screenshots that point to the exact problem of your customers to help you solve it easily. Attachments help you collect documents with visual data to understand questions in detail.
You should define what type of attachment you want and what is the limit of its size. The attachment can be of type JPG, PNG, PDF, and DOC type and the size can be less than 2MB or more. Limiting size helps you reduce the extra load on your server.
Let’s find out how you can collect attachments with your contact form using PHP with a valid file type and size.
How to Create PHP Contact Form with Attachment (Step-by-step)
Here is the step-by-step process on how to create PHP contact form with an attachment:-
Step 1: Create Contact Form Structure
First of all, you have to create a structure for your contact form to collect data from your customers. The data should be complete enough to help you know their queries and make one-to-one communication with them.
You can add fields like Name, Email, and Message to collect text content from customers. To collect attachments from your contact form, you can add <input type="file">
as shown below code.
Also, make all the fields required for users by adding required
attribute to all the form fields. This attribute makes all the fields compulsory to fill for users.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<div class="main-contact-form"> <form method="POST" id="ajaxform" action="" enctype="multipart/form-data"> <label for="Name">Your Name</label> <input type="text" name="name" placeholder="Enter name" required> <label for="Email">Your Email</label> <input type="email" name="email" placeholder="Enter email" required> <label for="message">Message</label> <textarea name="message" placeholder="Enter your message" rows="5" required></textarea> <label for="File">Upload File</label><br> <input type="file" name="file"><br><br> <input type="submit" class="btn btn-primary" name="submit" value="Submit"> </form> </div> |
The main structure of the contact form is shown in the image below. It contains a label with each form field and a submit button to submit the form.
The above contact form is a simple structure and will not looks better on your website. To make the design better, you must consider adding some CSS given in the next step.
Step 2: Add CSS to Make a Better Design
If you want to change the overall look and appearance of your contact form, you should consider adding some CSS code. The CSS should make all the form fields look better. It should also make the file field looks good and attractive to users.
Below is the complete CSS code that you have to add in the <head> section of your above HTML contact form design. Also, make sure the CSS code button color should match your brand. You can change the below code as per your requirements.
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 49 |
<style> input[type='text'],input[type='email'], textarea{ width: 100%; padding: 10px; border-radius: 3px; border: 1px solid #ccc; margin-top: 10px; margin-bottom: 20px; } input[type='text']:focus,input[type='email']:focus, textarea:focus{ border: 1px solid #5db6db; box-shadow: 0 0 10px #b9eaff; outline: none !important; } input[type='submit']{ background: rgb(39,160,210); color: #fff; border: none; padding: 10px 20px; cursor: pointer; } .main-contact-form{ max-width: 400px; margin: 0 auto; background: #e9e9e9; padding: 20px 45px 20px 25px; border-radius: 5px; } input[type=file] { width: 100%; padding: 5px; background: #fff; border-radius: 10px; border: 1px solid #ccc; } input[type=file]::file-selector-button { border: none; background: #084cdf; padding: 10px 20px; border-radius: 10px; color: #fff; cursor: pointer; transition: background .2s ease-in-out; } input[type=file]::file-selector-button:hover { background: #0d45a5; } </style> |
After you add some CSS, your contact form appearance will change as shown in the image below. It looks better and beautiful enough to add to your website. The upload button looks different and better to attract your customers.
The contact form also contains a background color to display the area it covers on a page on your website.
Step 3: Contact Form Email and File Validation Using PHP
You have to first collect all form data using PHP global variable $_POST
. However, to collect attachments, you have to use PHP global variable $_FILES
. After collecting the data, you can start validating them.
To validate the email address, you can match the user’s email address with the regular expression format. To validate the file attachment, you have to validate its file type and size.
The file type can be JPG, PNG, PDF, and Doc type for attachment. Its size can be 2MB or more and should be less to reduce the extra load on your server.
See the code below to validate your form data. It executes only when the users 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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<?php if(isset($_POST['submit'])){ // Get the submitted form data $email = $_POST['email']; $name = $_POST['name']; $message = $_POST['message']; //validation for email $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if (!preg_match($email_exp, $email)) { echo "The Email address you entered is not valid."; exit; } //Get uploaded file data using $_FILES array $tmp_name = $_FILES['file']['tmp_name']; // get the temporary file name of the file on the server $filename = $_FILES['file']['name']; // get the name of the file $filesize = $_FILES['file']['size']; // get size of the file for size validation $filetype = $_FILES['file']['type']; // get type of the file $fileerror = $_FILES['file']['error']; // get the error (if any) //validate form field for attaching the file if($fileerror > 0) { echo "Upload error or No files uploaded."; exit; } // Upload attachment file if(!empty($_FILES["file"]["name"])){ // File path config $targetDir = "uploads/"; $fileName = basename($filename); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); // Allow certain file formats $allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg'); if(in_array($fileType, $allowTypes)){ // Check file size if ($filesize > 2000000) { echo "File size should be less than 2MB"; exit; }else{ // Upload file to the server if(move_uploaded_file($tmp_name, $targetFilePath)){ $uploadedFile = $targetFilePath; }else{ echo "Sorry, there was an error uploading your file."; exit; } } }else{ echo "Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload."; exit; } } } ?> |
After the validation, you proceed further to send contact form data via email with an attachment.
Step 4: Send Contact Form Data with Attachment Via Email Using PHP (PHPMailer Gmail SMTP)
To send emails in PHP with attachments, the PHPMailer is the easiest method to use. It requires less coding and is easy to send attachments. I going to use Gmail SMTP which is free and easy to set up quickly.
Gmail SMTP is the most trusted mailer SMTP to send emails in PHP when you don’t have email services on your server. So, let’s set up it with the code given below.
Requirements to Setup PHPMailer Gmail SMTP
Firstly, download the PHPMailer by clicking on the button below and save it to the base location of your main files. Extract the folder to get all the PHPMailer required docs to send emails.
You will have to change the below things in the code given below to make it work:-
- Change ‘[email protected]’ with your Gmail id
- Change ‘yourgmailpassword’ with the app password of your Gmail id. You can read the guide Sign in with app password in Gmail to create your app password on Gmail.
- Change ‘[email protected]’ with the recipient’s email address. Also, change the ‘recipientname’ with your name to appear on the emails.
PHP Code to Send Emails Using PHPMailer Gmail SMTP
After you complete the above requirements, copy the below code and paste it after the validation code of PHP given in the previous step. The below code is self-explanatory and easy to understand with comments as it is well-commented.
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 49 50 51 52 53 |
<?php if(isset($_POST['submit'])){ //If everything above is ok then move further //Use PHPmailer require "phpmailer/PHPMailerAutoload.php"; $mail = new PHPMailer; //Mailbody to send in an email $mailbody = '<p><b>Customer contact details:-</b></p> <p><b>Name:</b> '.$name.'</p> <p><b>Email:</b> '.$email.'</p> <p><b>Message:</b> '.$message.'</p>'; //Sender email address $mail->isSMTP(); // Set mailer to use SMTP $mail->SMTPDebug = 0; //See errors, change it to 4 $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $sender; // SMTP username $mail->Password = 'yourgmailpassword';// Gmail SMTP password $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `SSL` also accepted $mail->Port = 587; // TCP port to connect to $mail->setFrom($email, $name); //$mail->addAddress('[email protected]'); //add more recipient (optional) $mail->addReplyTo($email, $name); //$mail->addCC('[email protected]'); //$mail->addBCC('[email protected]'); //Add attachment if(is_array($_FILES)) { $mail->AddAttachment($uploadedFile, $fileName, 'base64', 'mime/type'); } $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Contact Form Submitted by '.$name; $mail->Body = $mailbody; //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; //Email your contact form data with an attachment using Gmail SMTP with PHPMailer if(!$mail->send()){ echo "Message could not be sent. Please try again."; echo 'Mailer Error: ' . $mail->ErrorInfo; }else{ echo "Message has been sent successfully."; @unlink($uploadedFile); } } ?> |
After you have done with the above code and followed the requirements, you are all set!
Now, open the form on your favorite browser (mine is Google Chrome) and fill out the form and press the submit button to test it. You will see the emails received in your email inbox.
If you want to send emails without a page refresh, you can read our tutorial on Ajax Contact Form with Attachment in PHP (Using Mail() or PHP Mailer).
If you have any problem regarding sending emails or need any help, please comment below. I will be happy to help you.
You May Also Like to Read