Send Email with Attachment on Form Submission using PHP

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.

Web Form HTML with File Upload Field

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>

Send Email with attachment on Form Submission

The following code handles the form submission and email sending functionality using PHP.

  • Get the submitted form data using the $_POST method in PHP.
  • Validate input data to check whether the mandatory fields are not empty.
  • Validate email address using PHP FILTER_VALIDATE_EMAIL filter.
  • Check and validate the file extension to allow certain file formats (PDF, Image, and MS Word files).
  • Upload file to the server using PHP move_uploaded_file() function.
  • Add form data and uploaded file to the email content.
  • Send an email to the specified recipient with an attachment using the PHP mail() function.
<?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($emailFILTER_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($targetFilePathPATHINFO_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

Conclusion

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

17 Comments

  1. Rod Foley Said...
  2. Franco Cazzola Said...
    • CodexWorld Said...
  3. Solomon Said...
  4. Bill Said...
    • CodexWorld Said...
  5. Pratik Said...
  6. Francesco Said...
  7. Maria José Said...
  8. Bobbie Said...
  9. Ndam Lesly Said...
  10. Neon Santhosh Said...
  11. Wil Heeren Said...
  12. Dinesh Das Said...
  13. Danushka Madushan Said...
  14. Ruben Maesfranckx Said...

Leave a reply

keyboard_double_arrow_up