Search code examples
phpemailemail-attachments

php mail() : attachments sent but not body text


I have seen similar questions, but nothing directly on topic...

I have a multi part mail script with attachments. The attachments get sent fine, but the main body text, which is populated from a form, isn't sent. I tried sending with the attachment function commented out and the form elements went through. My code is:

if (empty($_POST['RadioGroup1'])){
    echo "PLease select a version of message";
} else {$selected_msg = $_POST['RadioGroup1'];} 

if (isset($_FILES) && (bool) $_FILES){
    $files = array();
// Check for attachments
    $questions = $_POST['questions'];   
//loop through all the files
  foreach($_FILES as $name=>$file){
// define the variables
    $file_name = $file['name'];
    $temp_name = $file['tmp_name'];
//check if file type allowed
    $path_parts = pathinfo($file_name);
//move this file to server
    $server_file = "reports/$path_parts[basename]";
    move_uploaded_file($temp_name, $server_file);
//add file to array of file
    array_push($files,$server_file);
}
// define mail var
$to   =  $email;
$from = "[server]";
$subject    = "Closed Case:  $case_id $casename";
$headers    = "From: $from";

//define boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

// Header know about boundary
 $headers .= "\nMIME-Version: 1.0\n";
 $headers .= "Content-Type: multipart/mixed;\n";
 $headers .= " boundary=\"{$mime_boundary}\""; 

// Define plain text mail
$message .= "--{$mime_boundary}\n";
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n" . $message . "\r\n"; 
$message .= "--{$mime_boundary}\n";

// preparing attachments
foreach($files as $file){
    $aFile = fopen($file, "rb");
    $data = fread($aFile,filesize($file));
    fclose($aFile);
    $data = chunk_split(base64_encode($data));
    $message .= "Content-Type: {\"application/octet-stream\"}\n";
    $message .= " name=\"$file\"\n";
    $message .= "Content-Disposition: attachment;\n";
    $message .= " filename=\"$file\"\n";
    $message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
    $message .= "--{$mime_boundary}\n";
} // END foreach attachment

    $message .= $questions;
    $message .= $selected_msg;


 $ok = @mail($to, $subject, $message, $headers); 
if ($ok) { 
    echo "<p class=\"success\">mail sent to $to!</p>";

The script runs without errors and does sent the file attachments OR the body text. Any insight would be appreciated.


Solution

  • Instead of calling the form variables from within ---

    $message .= $questions;.

    $message .= $selected_msg;
    Hard code the variables into the $message.=

    Like-- $message .= "Content-Transfer-Encoding: 7bit\r\n" . $questions . "\r\n" . $selected_msg . "\r\n";