The web form is a widely used element for web applications. Various types of forms are used on the website to submit user data. Contact, registration, and feedback forms are some of the most used web forms to get the user’s input. Generally, the text, textarea, and select input fields are used in the web form. But in some cases, the web form needs to be allowed the user to select a file. In this situation, you need to upload the selected file and attach it to the form data.
Contact or feedback form is used for online communication and the submitted form data is sent via email instantly. When the contact form has a file upload field, the file needs to be sent with email as an attachment. Using the mail() function, you can easily send email with attachment and form data in PHP. In this tutorial, we will show you how to send email with attachment on form submission using PHP.
The example code provides an instant ability to create a contact form with a file attachment option and integrate it into the website. Also, an email will be sent to a specific email address with a file attachment. For a better understanding, we will divide the PHP contact form with email and file attachment script into two parts, HTML (Web Form) and PHP (Form Submission). You can place both parts of the code together on the web page where you want to integrate the contact us form with a file attachment.
Create an HTML form with some basic contact fields (Name, Email, Subject, and Message) and a file input field. The file input field allows the user to select a file that will be sent as an attachment with the form data.
<!-- Display submission status --> <?php if(!empty($statusMsg)){ ?> <p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p> <?php } ?> <!-- Display contact form --> <form method="post" action="" enctype="multipart/form-data"> <div class="form-group"> <input type="text" name="name" class="form-control" value="<?php echo !empty($postData['name'])?$postData['name']:''; ?>" placeholder="Name" required=""> </div> <div class="form-group"> <input type="email" name="email" class="form-control" value="<?php echo !empty($postData['email'])?$postData['email']:''; ?>" placeholder="Email address" required=""> </div> <div class="form-group"> <input type="text" name="subject" class="form-control" value="<?php echo !empty($postData['subject'])?$postData['subject']:''; ?>" placeholder="Subject" required=""> </div> <div class="form-group"> <textarea name="message" class="form-control" placeholder="Write your message here" required=""><?php echo !empty($postData['message'])?$postData['message']:''; ?></textarea> </div> <div class="form-group"> <input type="file" name="attachment" class="form-control"> </div> <div class="submit"> <input type="submit" name="submit" class="btn" value="SUBMIT"> </div> </form>
The following code handles the form submission and email sending functionality using PHP.
<?php
// Email settings
$toEmail = 'admin@example.com'; // Recipient email
$from = 'sender@example.com'; // Sender email
$fromName = 'CodexWorld'; // Sender name
// File upload settings
$attachmentUploadDir = "uploads/";
$allowFileTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
/* Form submission handler code */
$postData = $uploadedFile = $statusMsg = $valErr = '';
$msgClass = 'errordiv';
if(isset($_POST['submit'])){
// Get the submitted form data
$postData = $_POST;
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
// Validate input data
if(empty($name)){
$valErr .= 'Please enter your name.<br/>';
}
if(empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$valErr .= 'Please enter a valid email.<br/>';
}
if(empty($subject)){
$valErr .= 'Please enter subject.<br/>';
}
if(empty($message)){
$valErr .= 'Please enter message.<br/>';
}
// Check whether submitted data is valid
if(empty($valErr)){
$uploadStatus = 1;
// Upload attachment file
if(!empty($_FILES["attachment"]["name"])){
// File path config
$targetDir = $attachmentUploadDir;
$fileName = basename($_FILES["attachment"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
// Allow certain file formats
if(in_array($fileType, $allowFileTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
$uploadedFile = $targetFilePath;
}else{
$uploadStatus = 0;
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$uploadStatus = 0;
$statusMsg = 'Sorry, only '.implode('/', $allowFileTypes).' files are allowed to upload.';
}
}
if($uploadStatus == 1){
// Email subject
$emailSubject = 'Contact Request Submitted by '.$name;
// Email message
$htmlContent = '<h2>Contact Request Submitted</h2>
<p><b>Name:</b> '.$name.'</p>
<p><b>Email:</b> '.$email.'</p>
<p><b>Subject:</b> '.$subject.'</p>
<p><b>Message:</b><br/>'.$message.'</p>';
// Header for sender info
$headers = "From: $fromName"." <".$from.">";
// Add attachment to email
if(!empty($uploadedFile) && file_exists($uploadedFile)){
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = @fopen($uploadedFile,"rb");
$data = @fread($fp,filesize($uploadedFile));
@fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $email;
// Send email
$mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
// Delete attachment file from the server
@unlink($uploadedFile);
}else{
// Set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
// Send email
$mail = mail($toEmail, $emailSubject, $htmlContent, $headers);
}
// If mail sent
if($mail){
$statusMsg = 'Thanks! Your contact request has been submitted successfully.';
$msgClass = 'succdiv';
$postData = '';
}else{
$statusMsg = 'Failed! Something went wrong, please try again.';
}
}
}else{
$valErr = !empty($valErr)?'<br/>'.trim($valErr, '<br/>'):'';
$statusMsg = 'Please fill all the mandatory fields.'.$valErr;
}
}
?>
Contact Form Popup with Email using Ajax and PHP
Our example code helps you to add a contact form with email sending and file attachment functionality on the website using PHP. But you can use this code for any type of web form to send form data through email with a file attachment. In the example code, we have allowed only .pdf, .doc, .docx, and Image files as an attachment. You can specify any type of file to upload and send it with the email on form submission.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Hi, I am using the code above and tried your demo, however after I complete the form on my host-page and upload the file, click submit, I get the following messag on the form:
Sorry, there was an error uploading your file
I am uploading an accepted type .jpg – Can you please assist with why this is coming up?
Thanks,
Rod
Hi
I tried to use your source code contact-form on localhost.
I get this message:
Warning: mail(): Failed to connect to mailservfer al localhost port 25, verify your SMTP and smtp_port setting in php.ini or use ini_set()
Please, what can I do ?
Franco
The PHP default mail() function will not work on localhost. You need to check the email functionality on the hosting server.
How to stop refresh after submit
I understand that the recipient is me, so I’d replace admin@example.com with my email address. But everyone who uses the form will have a different name and a different email address, so what would I replace sender@example.com with in the $from entry and CodeWorld with in the $fromName entry?
Yes, you need to specify the sender name in the
$fromName
variable and sender email in the$from
variable.Hi,
How do I add file size limit to attachment?
Kindly suggest.
Excellent script.
But to send more than one attachment, how can you modify it?
Thanks
This tutorial will help you – https://www.codexworld.com/send-email-with-multiple-attachments-php/
form works but how can i have it upload more than one file at a time?
form works but how can i have it upload more than one file at a time?
Thanks man. your tutorial helped me. Thanks.
it’s working fine thanks for this
how can i add recaptcha V2 to this form ?
How to add CC
nice it is working properly
Lifesaver!