Page 1 of 1

Attachment Encoding

Posted: Thu Sep 01, 2011 9:26 am
by MichiganJim
After a lot of effort, I have a script working to send email with attachments. The last hurdle seems to be in getting the encoding right.

My script below results in text versus the actual attachment. I've looked it over and over but can't see why the chunk_split(base64_encode($data)) isn't working for me.

Code: Select all

<?php
$to = 'Joe@Joe.com'; 
$from = 'Jim@Jim.com'; 
$sub = 'Test'; 
$filelist = '/Volumes/server/sites/thesite/some.jpg,/Volumes/server/sites/thesite/some.pdf';
$files = explode(",",$filelist);
$msg = lvMessage; 
$headers = "From: $from"; 

$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 
$msg = "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" . $msg . "\n\n"; 

// attachments code starts 
for($x=0;$x<count($files);$x++) 
{ 
$msg .= "–{$mime_boundary}\n"; 
$file = fopen($files[$x],"rb"); 
$data = fread($file,filesize($files[$x])); 
fclose($file); 
$data = chunk_split(base64_encode($data)); 
$msg .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" . 
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" . 
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; 
} 
$msg .= "–{$mime_boundary}–\n"; 
$res = @mail($to, $sub, $msg, $headers); 

?>