PHP: UTF-8 email with attachments

Since PHP 4.2.0, PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES[‘userfile’][‘error’].

$_FILES: An associative array of items uploaded to the current script via the HTTP POST method.

$attachments = "";
$semi_rand = md5(time()); 
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$number_of_files = count($_FILES);
$count = 0;
foreach ($_FILES as $file) {
  $count++;
  if (is_uploaded_file($file['tmp_name'])) {
    $handle = fopen($file['tmp_name'],'rb');
    $data = fread($handle, filesize($file['tmp_name']));
    fclose($handle);
 
    $data = chunk_split(base64_encode($data));
 
    $file_name = "=?UTF-8?B?" . base64_encode($file['name']) . "?=";
 
    $attachments .= "Content-Type: application/octet-stream;\n";
    $attachments .= " name=\"{$file_name}\"\n"; 
    $attachments .= "Content-Disposition: attachment;\n";
    $attachments .= " filename=\"{$file_name}\"\n"; 
    $attachments .= "Content-Transfer-Encoding: base64\n\n";
    $attachments .= $data . "\n\n";
 
    if ($count == $number_of_files) {
      $attachments .= "--{$mime_boundary}--\n";
    } else {
      $attachments .= "--{$mime_boundary}\n";
    }
  }
}
 
// UTF-8 subject
$subject = "Subject";
$subject = "=?UTF-8?B?" . base64_encode($subject) . "?=\n";
 
$mime_boundary = empty($attachments) ? md5(date('r', time())) : $mime_boundary;
 
$to = "=?UTF-8?B?" . base64_encode($to_name) . "?= <". $to_email . ">";
 
// UTF-8 header	
$header  = "From: =?UTF-8?B?" . base64_encode($from_name) . "?= <" . $from_email . ">\r\n";
 
if (!empty($cc_name) {
  $header .= "Cc: =?UTF-8?B?" . base64_encode($cc_name) . "?= <" . $cc_email . ">\r\n";
}
 
if (!empty($bcc_name) {
  $header .= "Bcc: =?UTF-8?B?" . base64_encode($bcc_name) . "?= <" . $bcc_email . ">\r\n";
}
 
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"{$mime_boundary}\"\r\n";
 
// Compose message
$body  = "This is a multi-part message in MIME format.\n\n";
$body .= "--{$mime_boundary}\n";
$body .= "Content-Type: text/html; charset=\"UTF-8\"\n";
$body .= "Content-Transfer-Encoding: 8bit\n\n";
$body .= "Mail content\n\n";
if (empty($attachments)) {
  $body .= "--{$mime_boundary}--\n";
} else {
  $body .= "--{$mime_boundary}\n";
  $body .= $attachments;
}

Leave a Reply