Contact Form with Sending Email with Attachment in 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 allow 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 via email as an attachment. Using the mail() function, you can easily send an email with attachments and form data in PHP. In this tutorial, we will show you how to send email with attachment on form submission using PHP.

This example code snippet 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.

HTML Web Form with File Upload Field

Create an HTML form with some input elements (common contact fields: Name, Email, Subject, and Message) and a file input field.

  • Set enctype="multipart/form-data" in the form tag to allow file uploads.
  • Input type="file" allows users to select a file from their device. The accept attribute specifies the allowed file types (PDF, Image, and MS Word files in this case).

Display the form submission status (success or error messages) above the form.

  • If the form submission fails fill the input fields with the previously submitted values using PHP $_POST superglobal array.
  • Use PHP htmlspecialchars() to prevent XSS attacks by escaping special characters in user input.
<!-- Display form submission status -->
<?php if (!empty($errors)): ?>
    <div class="status-msg error">
        <ul>
            <?php foreach ($errors as $error): ?>
                <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php elseif ($success): ?>
    <div class="status-msg success">
        <?php echo htmlspecialchars($success); ?>
    </div>
<?php endif; ?>

<!-- Contact form fields -->
<form action="" method="post" enctype="multipart/form-data" autocomplete="off">
    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" id="name" name="name" required placeholder="Your name" value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>">
    </div>
    <div class="form-group">
        <label for="email">Email</label>
        <input type="email" id="email" name="email" required placeholder="ex: your@email.com" value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
    </div>
    <div class="form-group">
        <label for="subject">Subject</label>
        <input type="text" id="subject" name="subject" required placeholder="Enter subject" value="<?php echo htmlspecialchars($_POST['subject'] ?? ''); ?>">
    </div>
    <div class="form-group">
        <label for="message">Message</label>
        <textarea id="message" name="message" required placeholder="Type your message..."><?php echo htmlspecialchars($_POST['message'] ?? ''); ?></textarea>
    </div>
    <div class="form-group">
        <label for="file">Attachment</label>
        <input type="file" id="file" name="attachment" accept=".pdf,.doc,.docx,.jpg,.png,.jpeg">
    </div>
    <input type="submit" name="submit" value="Send Message">
</form>

Form Submission and Email Sending with Attachment using PHP

The following PHP script processes the form submission, validates the input data, handles the file upload, and sends an email with the form data and the uploaded file as an attachment.

  • Retrieve the submitted form data using the $_POST superglobal array.
  • Validate the input data to ensure that mandatory fields are not empty and that the email address is in a valid format using the PHP FILTER_VALIDATE_EMAIL filter.
  • Validate the file extension to allow only certain file formats (PDF, Image, and MS Word files).
  • Check file size to ensure it does not exceed the specified limit (e.g., 5MB).
  • Send email to the specified recipient with the form data and the uploaded file as an attachment using the PHP mail() function.

Note: The following PHP code snippet should be placed at the top of the same file where the HTML form is located or in a separate PHP file that handles the form submission.

<?php 
// Define admin email
$admin_email "admin@example.com"// Change to your admin email

// Initialize variables
$errors = [];
$success "";

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
    
// Name validation
    
$name trim($_POST["name"] ?? "");
    if (empty(
$name)) {
        
$errors['name'] = "Name is required.";
    } elseif (!
preg_match("/^[a-zA-Z\s]+$/"$name)) {
        
$errors['name'] = "Name can only contain letters and spaces.";
    }

    
// Email validation
    
$email trim($_POST["email"] ?? "");
    if (empty(
$email)) {
        
$errors['email'] = "Email is required.";
    } elseif (!
filter_var($emailFILTER_VALIDATE_EMAIL)) {
        
$errors['email'] = "Invalid email format.";
    }

    
// Subject validation
    
$subject trim($_POST["subject"] ?? "");
    if (empty(
$subject)) {
        
$errors['subject'] = "Subject is required.";
    }

    
// Message validation
    
$message trim($_POST["message"] ?? "");
    if (empty(
$message)) {
        
$errors['message'] = "Message is required.";
    }

    
// File validation
    
$attachment $_FILES['attachment'] ?? null;
    
$allowed_types = ['application/pdf''application/msword''application/vnd.openxmlformats-officedocument.wordprocessingml.document''image/jpeg''image/png'];
    if (
$attachment && $attachment['error'] !== 4) { // 4 = no file uploaded
        
if ($attachment['error'] !== 0) {
            
$errors['attachment'] = "Error uploading file.";
        } elseif (!
in_array($attachment['type'], $allowed_types)) {
            
$errors['attachment'] = "Invalid file type. Allowed: PDF, DOC, DOCX, JPG, PNG.";
        } elseif (
$attachment['size'] > 1024 1024) {
            
$errors['attachment'] = "File size must be less than 5MB.";
        }
    }

    
// If no errors, send email
    
if (empty($errors)) {
        
$boundary md5(time());
        
$headers "From: {$name} <{$email}>\r\n";
        
$headers .= "Reply-To: {$email}\r\n";
        
$headers .= "MIME-Version: 1.0\r\n";
        
$headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";

        
// HTML email body
        
$htmlContent '
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; color: #333; }
                .email-container { background: #f9f9f9; padding: 24px; border-radius: 8px; }
                .email-header { font-size: 1.2rem; font-weight: bold; margin-bottom: 12px; color: #007bff; }
                .email-row { margin-bottom: 10px; }
                .email-label { font-weight: bold; color: #555; }
                .email-message { margin-top: 18px; }
            </style>
        </head>
        <body>
            <div class="email-container">
                <div class="email-header">New Contact Form Submission</div>
                <div class="email-row"><span class="email-label">Name:</span> ' 
htmlspecialchars($name) . '</div>
                <div class="email-row"><span class="email-label">Email:</span> ' 
htmlspecialchars($email) . '</div>
                <div class="email-row"><span class="email-label">Subject:</span> ' 
htmlspecialchars($subject) . '</div>
                <div class="email-message"><span class="email-label">Message:</span><br>' 
nl2br(htmlspecialchars($message)) . '</div>
            </div>
        </body>
        </html>
        '
;

        
// Multipart message
        
$body "--{$boundary}\r\n";
        
$body .= "Content-Type: text/html; charset=UTF-8\r\n";
        
$body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
        
$body .= $htmlContent "\r\n";

        
// Attachment
        
if ($attachment && $attachment['error'] === 0) {
            
$file_content chunk_split(base64_encode(file_get_contents($attachment['tmp_name'])));
            
$file_name basename($attachment['name']);
            
$file_type $attachment['type'];

            
$body .= "--{$boundary}\r\n";
            
$body .= "Content-Type: {$file_type}; name=\"{$file_name}\"\r\n";
            
$body .= "Content-Disposition: attachment; filename=\"{$file_name}\"\r\n";
            
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
            
$body .= $file_content "\r\n";
        }

        
$body .= "--{$boundary}--";

        
// Send email
        
if (mail($admin_email"Contact Form: " $subject$body$headers)) {
            
$success "Your message has been sent successfully!";
            
            
// Clear form data
            
$_POST = [];
        } else {
            
$errors['form'] = "Failed to send your message. Please try again later.";
        }
    }
}
?>

Notes:

  • Change the value of the $admin_email variable to your desired recipient email address.
  • Make sure your server is configured to send emails using the PHP mail() function. If you are using a local server (like XAMPP, WAMP, etc.), you may need to set up an SMTP server or use a third-party email service.
  • Ensure that the file upload size limit in your PHP configuration (php.ini) allows for the size of files you expect users to upload. You may need to adjust the upload_max_filesize and post_max_size settings.

Code Explanation

  • We have created a simple HTML form with fields for name, email, message, and file attachment. The form uses the POST method to submit data to the same page.
  • In the PHP section, we check if the form is submitted using $_SERVER["REQUEST_METHOD"] == "POST".
  • We retrieve the form data using the $_POST superglobal array and sanitize it using htmlspecialchars() to prevent XSS attacks.
  • We handle the file upload using the $_FILES superglobal array. We check for errors, validate the file type and size, and move the uploaded file to a designated directory on the server.
  • We prepare the email headers and body, including the attachment if a file was uploaded successfully.
  • Finally, we use the mail() function to send the email with or without the attachment based on whether a file was uploaded.

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 attachments. You can specify any type of file to upload and send it with the email on form submission.

Looking for expert assistance to implement or extend this script’s functionality? Submit a 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

construction Need this implemented in your project? Request Implementation Help → keyboard_double_arrow_up