Send upload file email attachment php

This tutorial explains how to send the uploaded file email attachment php. The below code shows how to send the uploaded file as an email attachment using php code.

This example gives step by step explanation for accessing the file from the form and preparing the email with message body and attachment. Please also refer other tutorial which explains how to send the all the files in a folder as attachment.


send_uploaded_file_email_attachment_php

Main steps are :

  • Create the form
  • Retrieve Uploaded File
  • Prepare email message body
  • Prepare email attachment
  • Send uploaded file as email attachment

Create the form

As the first step create the form with name,email and upload fields.The name and email fields are send as part of the message body and file as attachment.

<div class="wrap">
    <h3>Upload File and send as email attachment</h3>
    <form method="POST" name="sendemail" action="sendemail.php" enctype="multipart/form-data"> 
        <div>
            <label for='name'>Name: </label>
            <input type="text" name="name" ><br/>
        </div>
        <div>
            <label for='email'>Email: </label>
            <input type="text" name="email" ><br/>
        </div>
        <div>
            <label for='uploaded_file'>Select A File To Upload:</label>
            <input type="file" name="uploaded_file"></br>
        </div>
        <input type="submit" value="Submit" name='submit'>
    </form>
</div>

Retrieve Upload file

This step get the file from the post data and validate the file extension and sizes.

$name_of_uploaded_file =basename($_FILES['uploaded_file']['name']);
$formData = $_POST;
getFile( $name_of_uploaded_file, $formData );
function getFile( $filename , $formData ) {
    
    $allowedExts = array("csv","pdf");
    $temp = explode(".", $_FILES["uploaded_file"]["name"]);
    $extension = end($temp);
    $mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');

    if (in_array($_FILES['uploaded_file']['type'],$mimes )
    && ($_FILES["uploaded_file"]["size"] < 2000000)
    && in_array($extension, $allowedExts))
      {
      if ($_FILES["uploaded_file"]["error"] > 0)
        {
        echo "Return Code: " . $_FILES["uploaded_file"]["error"] . "<br>";
        }
      else
        {      
            sendMailAsAttachment($_FILES["uploaded_file"]["tmp_name"],$_FILES["uploaded_file"]["name"],$formData);         
        }
      }
    else
      {
      echo "Invalid file";
      }  
}

Prepare email message body

This function accepts post data on form submissions and prepare the email message from the form data.

function prepareEmail( $formData ) {
    
    // email fields: to, from, subject, and so on
    $to = "test@gmail.com";
    $from = "admin@admin.com"; 
    $subject =""; 
    $message = "Uploaded File\n";
    $message .= "Name :". $formData['name']."\n";
    $message .= "Email Address :". $formData['email']."\n";
    $headers = "From: $from";

    // 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 .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; 
    $message .= "--{$mime_boundary}\n";
    
    $emailData = array (
        'to' => $to,
        'from' => $from,
        'subject' => $subject,
        'headers' => $headers,
        'message' => $message
    );
    
    return $emailData;
    
}

Prepare email attachment

This function reads data from the upload file and prepare email attachment.

function pepareAttachment( $filename ,$fileorgname) {
    $attachContent = '';
    $file = fopen($filename,"rb");
    $data = fread($file,filesize($filename));
    fclose($file);
    $cvData = chunk_split(base64_encode($data));
    $attachContent .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$fileorgname\"\n" . 
    "Content-Disposition: attachment;\n" . " filename=\"$fileorgname\"\n" . 
    "Content-Transfer-Encoding: base64\n\n" . $cvData . "\n\n";
    $attachContent .= "--{$mime_boundary}\n"; 
    return $attachContent;
    
}

Send uploaded file as email attachment

function sendMailAsAttachment( $filename, $fileorgname, $formData ) {
    
    $emailData = prepareEmail( $formData );
    $attachContent = prepareAttachment( $filename,$fileorgname );
    $message = $emailData['message'].$attachContent;
    $ok = @mail($emailData['to'], $emailData['subject'], $message, $emailData['headers']); 
    if ($ok) { 
            echo "<p>mail sent to $to!</p>"; 
    } else { 
            echo "<p>mail could not be sent!</p>"; 
    } 
}

Please also refer other tutorial which explains how to send the all the files in a folder as attachment.

Share this Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

*