user2851129 user2851129 - 1 month ago 9
PHP Question

attachment is not working in mail function wordpress

Text mail works fine but I want to attach file too.
Attachment is not working.
My code is:

<form method="post" enctype="multipart/form-data">
<input name="filepc" type="file" id="filepc" class="listEm" />
</form>


if (isset($_POST['submit'])) {
$attachments = '';
if (!empty($_FILES['filepc']['tmp_name'])) {
$attachments = array($_FILES['filepc']['name']);

}

headers = "From:" . $your_email . " < " . $email . ">" . "\r\n";
$headers .= "Reply - To:" . $ct_email . "\r\n";
$headers .= "Content-Disposition: attachment; filename=\"".$attachments."\"\r\n\r\n";
//$headers = "Bcc: someone@domain . com" . "\r\n";
$headers = "X - Mailer: PHP / " . phpversion();
mail($to , $subject , $msg , $headers,$attachments);
$successMsg = '<h5 style="color:red;">Sent successfully</h5>';
// }

}


Above code works but file is not attached. Please help me find the solution for this problem.

Answer
if(!empty($_FILES['resume']['name'])) {
    $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
    $tmp_name = $_FILES['resume']['tmp_name'];
    $type = $_FILES['resume']['type'];
    $file_name = $_FILES['resume']['name'];
    $size = $_FILES['resume']['size'];

    // Check to make sure that it is an uploaded file and not a system file
    if(is_uploaded_file($tmp_name)){
        // Now Open the file for a binary read
        $file = fopen($tmp_name,'rb');
        // Now read the file content into a variable
        $data = fread($file,filesize($tmp_name));
        // close the file
        fclose($file);
        // Now we need to encode it and split it into acceptable length lines
        $data = chunk_split(base64_encode($data));
    }
    $mybody = "This is a multi-part message in MIME format.\n\n" .
         "--{$mime_boundary}\n" .
         "Content-Type: text/html; charset=\"iso-8859-1\"\n" .
         "Content-Transfer-Encoding: 7bit\n\n" .
    $mybody . "\n\n";

    $headers = "From: $from\r\n" .
         "MIME-Version: 1.0\r\n" .
         "Content-Type: multipart/mixed;\r\n" .
         " boundary=\"{$mime_boundary}\"";

    $mybody .= "--{$mime_boundary}\n" .
         "Content-Type: {$type};\n" .
         " name=\"{$file_name}\"\n" .
         //"Content-Disposition: attachment;\n" .
         //" filename=\"{$fileatt_name}\"\n" .
         "Content-Transfer-Encoding: base64\n\n" .
        $data . "\n\n" .
        "--{$mime_boundary}--\n";

    $bodys .= "$mybody <br>";
    $subject = "Attachment";
    $body = $body . $bodys;
    mail($to, $subject, $body, $headers);
}