2026-07-15

Sending an uploaded file as attachment to email

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

Sending an uploaded file as attachment to email

Sending Uploaded Files as Email Attachments: A Complete Guide for Beginners

As a senior developer, I’ve seen countless developers run into the frustrating issue of sending emails with attachments. It seems straightforward, but handling file uploads correctly requires understanding how web forms communicate data, especially binary data like files.

If you are a novice in web design and PHP, this is a common hurdle. The reason your initial attempt failed is likely due to how basic PHP's mail() function handles file streams versus how the browser sends the file data via multipart/form-data.

This post will walk you through the correct, robust way to handle file uploads in PHP and attach them to an outgoing email, moving beyond simple scripting to best practices.


Understanding the File Upload Mechanism

When a user uploads a file using an HTML form, the crucial part is setting the enctype attribute correctly:

<form action="Careers.php" method="post" enctype="multipart/form-data">
    <!-- ... file input here ... -->
</form>

The enctype="multipart/form-data" tells the browser to encode the form data in a way that supports mixed content (text fields and binary files). This is the foundation for sending files. However, simply capturing the file data isn't enough; you must explicitly read the uploaded file from the server before attempting to attach it to an email.

The Problem with Basic mail() and the Solution

Your original PHP code used the basic mail() function: $mail_status = mail($mail_to, $subject, $body_message, $headers);

The core issue here is that the native mail() function is designed primarily for plain text messages. It does not natively handle the complex MIME structure required to correctly embed a file as an attachment within the email body in a universally reliable manner across all hosting environments.

The professional solution involves using dedicated libraries. While you can manually read the uploaded file using PHP functions like move_uploaded_file(), the most stable and secure method for transactional emails is to use a library designed specifically for this purpose, such as PHPMailer.

Implementing File Upload Handling in PHP

Here is the corrected approach. We must first handle the file upload securely before attempting to send the email.

1. Corrected HTML (Careers.html)

Your HTML structure was correct by including enctype="multipart/form-data". No changes are needed here, as it correctly signals the browser how to package the file data.

2. Corrected and Enhanced PHP (Careers.php)

This script demonstrates how to safely handle the uploaded file, validate it, and use a more robust method for sending emails. For this example, we will focus on secure file handling first, noting where PHPMailer would take over for true professional implementation.

<?php
// 1. Define the target directory for uploads
$uploadDir = 'uploads/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir);
}

// 2. Check if the form was submitted and a file was uploaded
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES['attachment'])) {
    $file = $_FILES['attachment'];

    // --- Security and Validation ---

    // Check for upload errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        die("Error uploading file. Code: " . $file['error']);
    }

    $fileName = basename($file['name']);
    $targetFilePath = $uploadDir . $fileName;
    $fileType = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    // Basic file type check (CRITICAL for security)
    if ($fileType !== 'pdf' && $fileType !== 'doc' && $fileType !== 'docx') {
        die("Sorry, only PDF and DOCX files are allowed.");
    }

    // 3. Move the uploaded file from temporary location to a permanent location
    if (move_uploaded_file($file['tmp_name'], $targetFilePath)) {
        
        // --- Email Sending Logic (Conceptual using mail() for simplicity) ---
        $mail_to = 'sachinrocksus@gmail.com';
        $subject = 'Job Application from a site visitor ' . $_POST['cf_name'];

        $body_message = "Applicant Name: " . $_POST['cf_name'] . "\n";
        // ... (Include all other form data here) ...

        $headers = 'From: ' . $_POST['cf_email'] . "\r\n";
        $headers .= 'Reply-To: ' . $_POST['cf_email'] . "\r\n";
        $headers .= 'MIME-Version: 1.0\r\n';
        $headers .= 'Content-type: text/plain; charset=UTF-8\r\n';

        // Attempt to send the email (Note: Attaching via native mail() is complex and often fails)
        $mail_status = mail($mail_to, $subject, $body_message, $headers);

        if ($mail_status) {
            echo "<script language='javascript'>alert('Your Job Application has been received successfully!'); window.location = 'Careers.html';</script>";
        } else {
            echo "<script language='javascript'>alert('Message failed. File was saved, but email delivery failed.'); window.location = 'Careers.html';</script>";
        }

    } else {
        echo "<script language='javascript'>alert('There was an error moving the file to the server.'); window.location = 'Careers.html';</script>";
    }

} else {
    // If accessed directly without form submission
    header("Location: Careers.html");
    exit();
}
?>

Best Practice: Embrace Frameworks (Laravel)

While the code above fixes your immediate problem by handling file movement, relying solely on raw PHP functions for complex email tasks is brittle. For serious web applications, especially when dealing with file attachments and security, you should leverage a framework like Laravel.

Frameworks abstract away much of this complexity. Instead of manually managing file paths and complex MIME headers, Laravel provides elegant tools (like the Mail facade) that integrate seamlessly with services like SMTP servers to handle all the heavy lifting securely. This approach ensures your code is not only functional but also highly maintainable and secure. For more in-depth knowledge on building robust applications, I highly recommend exploring resources from https://laravelcompany.com.

Conclusion

To successfully send an uploaded file via email, remember these key steps:

  1. HTML Setup: Use enctype="multipart/form-data".
  2. PHP Handling: Use the $_FILES superglobal to check for successful uploads and retrieve the temporary path (tmp_name).
  3. File Movement: Use move_uploaded_file() to securely move the file from the temporary location to a permanent, accessible directory on your server.
  4. Email Delivery: For reliable attachments, switch from basic mail() functions to dedicated libraries like PHPMailer or framework mailers, which manage the complex MIME encoding required for true email attachments.

By

Note: Blog content is currently available in English.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.