PHP Send Attachment With Email

Last Updated : 11 Jul, 2025

Sending an email is a very common activity in a web browser. For example, sending an email when a new user joins a network, sending a newsletter, sending greeting mail, or sending an invoice. We can use the built-in mail() function to send an email programmatically. This function needs three required arguments that hold the information about the recipient, the subject of the message and the message body. Along with these three required arguments, there are two more arguments which are optional. One of them is the header and the other one is parameters. 
We have already discussed sending text-based emails in PHP in our previous article. In this article, we will see how we can send an email with attachments using the Mime-Versionmail() function.
When the mail() function is called PHP will attempt to send the mail immediately to the recipient then it will return true upon successful delivery of the mail and false if an error occurs.
Syntax
 

bool mail( $to, $subject, $message, $headers, $parameters );


Here is the description of each parameter. 
 

NameDescriptionRequired/OptionalType
toThis contains the receiver or receivers of the particular emailRequiredString
subjectThis contains the subject of the email. This parameter cannot contain any newline charactersRequiredString
messageThis contains the message to be sent. Each line should be separated with an LF (\n). Lines should not exceed 70 characters (We will use wordwrap() function to achieve this.)RequiredString
headersThis contains additional headers, like From, Cc, Mime Version, and Bcc.OptionalString
parametersSpecifies an additional parameter to the send mail programOptionalString


When we are sending mail through PHP, all content in the message will be treated as simple text only. If we put any HTML tag inside the message body, it will not be formatted as HTML syntax. HTML tag will be displayed as simple text. 
To format any HTML tag according to HTML syntax, we can specify the MIME (Multipurpose Internet Mail Extension) version, content type and character set of the message body. 
To send an attachment along with the email, we need to set the Content-type as mixed/multipart and we have to define the text and attachment sections within a Boundary.

Approach: Make sure you have a XAMPP server or WAMP server installed on your machine. In this article, we will be using the WAMP server.

Follow the steps given below:

Create an HTML form: Below is the HTML source code for the HTML form. In the HTML <form> tag, we are using "enctype='multipart/form-data" which is an encoding type that allows files to be sent through a POST method. Without this encoding, the files cannot be sent through the POST method. We must use this enctype if you want to allow users to upload a file through a form.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href=
"https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
    <title>Send Attachment With Email</title>
</head>

<body>
    <div style="display:flex; justify-content: center; margin-top:10%;">
        <form enctype="multipart/form-data" 
              method="POST" 
              action="" style="width: 500px;">
            <div class="form-group">
                <input class="form-control" 
                       type="text" 
                       name="sender_name" 
                       placeholder="Your Name" required />
            </div>
            <div class="form-group">
                <input class="form-control" 
                       type="email" name="sender_email" 
                       placeholder="Recipient's Email Address"
                    required />
            </div>
            <div class="form-group">
                <input class="form-control" 
                       type="text" 
                       name="subject" 
                       placeholder="Subject" />
            </div>
            <div class="form-group">
                <textarea class="form-control" 
                          name="message" 
                          placeholder="Message"></textarea>
            </div>
            <div class="form-group">
                <input class="form-control" 
                       type="file" 
                       name="attachment" 
                       placeholder="Attachment" required />
            </div>
            <div class="form-group">
                <input class="btn btn-primary" 
                       type="submit" 
                       name="button" 
                       value="Submit" />
            </div>
        </form>
    </div>
</body>

</html>

PHP Script for handling the form data:  

PHP
<?php

// Check if form is submitted and file is uploaded
if (isset($_POST['button']) && isset($_FILES['attachment'])) {

    // Define sender and recipient emails
    $from_email = 'sender@abc.com'; // Sender email
    $recipient_email = 'recipient@xyz.com'; // Recipient email

    // Load POST data from form
    $sender_name = $_POST["sender_name"]; // Sender's name
    $reply_to_email = $_POST["sender_email"]; // Reply-to email
    $subject = $_POST["subject"]; // Email subject
    $message = $_POST["message"]; // Email body

    // Validate sender name (uncomment for validation)
    // if (strlen($sender_name) < 1) {
    //     die('Name is too short or empty!');
    // }

    // Get uploaded file data
    $tmp_name = $_FILES['attachment']['tmp_name']; // Temp file path
    $name = $_FILES['attachment']['name']; // Original file name
    $size = $_FILES['attachment']['size']; // File size
    $type = $_FILES['attachment']['type']; // File type
    $error = $_FILES['attachment']['error']; // Upload error

    // Check for upload errors
    if ($error > 0) {
        die('Upload error or no file uploaded');
    }

    // Read the file and encode its content
    $handle = fopen($tmp_name, "r"); // Open file for reading
    $content = fread($handle, $size); // Read file content
    fclose($handle); // Close file

    // Base64 encode the file content and define boundary
    $encoded_content = chunk_split(base64_encode($content)); // Encode content
    $boundary = md5("random"); // Generate a unique boundary

    // Define email headers
    $headers = "MIME-Version: 1.0\r\n"; // Specify MIME version
    // Set sender email
    $headers .= "From: " . $from_email . "\r\n";
    // Set reply-to email
    $headers .= "Reply-To: " . $reply_to_email . "\r\n";
    // Set content type and boundary
    $headers .= "Content-Type: multipart/mixed; boundary=$boundary\r\n";

    // Construct email body with message and attachment
    $body = "--$boundary\r\n";
    $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $body .= chunk_split(base64_encode($message)); // Encode message

    // Add attachment to the email body
    $body .= "--$boundary\r\n";
    $body .= "Content-Type: $type; name=\"$name\"\r\n";
    $body .= "Content-Disposition: attachment; filename=\"$name\"\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n";
    $body .= "X-Attachment-Id: " . rand(1000, 99999) . "\r\n\r\n";
    $body .= $encoded_content; // Append encoded file content

    // Send the email
    $sentMailResult = mail($recipient_email, $subject, $body, $headers);

    // Check if the email was sent successfully
    if ($sentMailResult) {
        echo "<h3>File sent successfully.</h3>";
        // Optionally delete the file after sending
        // unlink($name);
    } else {
        die("Sorry, the email could not be sent. Please try again.");
    }
}

Complete Code: The final code for sending attachments with Emails is as follows:

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" 
          href=
"https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
    <title>Send Attachment With Email</title>
</head>

<body>
    <div style="display: flex; justify-content: center; margin-top: 10%;">
        <form enctype="multipart/form-data" 
              method="POST" action="" 
              style="width: 500px;">
            <div class="form-group">
                <input class="form-control" 
                       type="text" name="sender_name" 
                       placeholder="Your Name" required>
            </div>
            <div class="form-group">
                <input class="form-control" 
                       type="email" name="sender_email" 
                       placeholder="Recipient's Email Address"
                    required>
            </div>
            <div class="form-group">
                <input class="form-control" 
                       type="text" 
                       name="subject" 
                       placeholder="Subject">
            </div>
            <div class="form-group">
                <textarea class="form-control" 
                          name="message" 
                          placeholder="Message">
                </textarea>
            </div>
            <div class="form-group">
                <input class="form-control" 
                       type="file" 
                       name="attachment" 
                       placeholder="Attachment" required>
            </div>
            <div class="form-group">
                <input class="btn btn-primary" 
                       type="submit" 
                       name="button" 
                       value="Submit">
            </div>
        </form>
    </div>
</body>

</html>
PHP
<?php

// Check if form is submitted and file is uploaded
if (isset($_POST['button']) && isset($_FILES['attachment'])) {

    // Define sender and recipient emails
    $from_email = 'sender@abc.com'; // Sender email
    $recipient_email = 'recipient@xyz.com'; // Recipient email

    // Load POST data from HTML form
    $sender_name = $_POST["sender_name"]; // Sender's name
    $reply_to_email = $_POST["sender_email"]; // Reply-to email
    $subject = $_POST["subject"]; // Email subject
    $message = $_POST["message"]; // Email body

    // Validate sender name (uncomment for validation)
    // if (strlen($sender_name) < 1) {
    //     die('Name is too short or empty!');
    // }

    // Get uploaded file data
    $tmp_name = $_FILES['attachment']['tmp_name']; // Temp file path
    $name = $_FILES['attachment']['name']; // Original file name
    $size = $_FILES['attachment']['size']; // File size
    $type = $_FILES['attachment']['type']; // File type
    $error = $_FILES['attachment']['error']; // Upload error

    // Check for upload errors
    if ($error > 0) {
        die('Upload error or no file uploaded');
    }

    // Read the file and encode its content
    $handle = fopen($tmp_name, "r"); // Open file for reading
    $content = fread($handle, $size); // Read file content
    fclose($handle); // Close file

    $encoded_content = chunk_split(base64_encode($content)); // Encode content
    $boundary = md5("random"); // Generate a unique boundary

    // Define email headers
    $headers = "MIME-Version: 1.0\r\n"; // Specify MIME version
    // Set sender email
    $headers .= "From: " . $from_email . "\r\n";
    // Set reply-to email
    $headers .= "Reply-To: " . $reply_to_email . "\r\n";
    // Set content type and boundary
    $headers .= "Content-Type: multipart/mixed; boundary=$boundary\r\n";

    // Construct email body with message and attachment
    $body = "--$boundary\r\n";
    $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $body .= chunk_split(base64_encode($message)); // Encode message

    // Add attachment to the email body
    $body .= "--$boundary\r\n";
    $body .= "Content-Type: $type; name=\"$name\"\r\n";
    $body .= "Content-Disposition: attachment; filename=\"$name\"\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n";
    $body .= "X-Attachment-Id: " . rand(1000, 99999) . "\r\n\r\n";
    $body .= $encoded_content; // Append encoded file content

    // Send the email
    $sentMailResult = mail($recipient_email, $subject, $body, $headers);

    // Check if the email was sent successfully
    if ($sentMailResult) {
        echo "<h3>File sent successfully.</h3>";
        // Optionally delete the file after sending
        // unlink($name);
    } else {
        die("Sorry, the email could not be sent. Please try again.");
    }
}

Output: 

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

Comment