Sending email attachments with PHP and mail()
After spending an entire day googling for answers to this problem - all I wanted was a simple and easy script to send attachments, without installing any modules...I finally got mail() to work for sending attachments. Part of the problem, weirdly, was the trailing carriage returns at the end of the headers - there was one or two extras, and it corrupted the attachment. Once I got that straightened out, and the headers, it worked much better. In any case, I'm posting the code directly so that if you are doing the same thing, you can just chop it up and paste it without spending as much time on it as I did. Another note: most emailers use two sets of headers for the text/html content and attachment, but it seems to work fine like this. Since the file content is base64 encoded, the attachment type is hard-coded to be application/octet-stream.
function send_mail_with_attachment($filename, $filepath, $to, $subject, $body, $from = "Mr. Return Address ") {
//$data = return_file($filename);
$file = fopen($filepath,'rb');
$data = fread($file, filesize($filepath) );
fclose($file);
$data = chunk_split(base64_encode($data));
$boundary = uniqid("JONAHMAIL");
$boundary2 = uniqid("JONAHATTACH");
//--------------------------------------------------------------------------
$headers = "From: " . $from . "\n";
$headers .= "Reply-To: " . $from . "\n";
$headers .= "MIME-Version: 1.0\n";
//$headers .= "Content-Transfer-Encoding: 8bit\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary2\";\n\n";
//
////$headers .= "This is a multi-part message in MIME format.\n\n";
////$message .= "Content-Type: multipart/alternative; boundary=\"$boundary\"\n";
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
////$message .= "\n\n--$boundary\n";
$headers .= "charset=iso-8859-1\n";////
////$message .= "Content-Type: text/plain; charset=iso-8859-1\n";
$headers .= "Content-Transfer-Encoding: 7bit\n\n";
$headers .= strip_tags($body) . "\r\n\r\n";
//$headers .= chunk_split(base64_encode(strip_tags($body))) . "\r\n\r\n";
$headers .= "\n\n--$boundary2\n";
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
$headers .= "Content-Transfer-Encoding: 7bit\n\n";
$headers .= $body;
////$headers .= "\n\n--$boundary--\n\n\n";
//Attachment
$headers .= "\n\n--$boundary2\n";
$headers .= "Content-Type: \"application/octet-stream\"; name=\"$filename\"\n";
$headers .= "Content-Transfer-Encoding: base64\n";
$headers .= "Content-Description: $filename\n";
$headers .= "Content-Disposition: attachment; filename=\"$filename\"\n\n";
$headers .= $data;
$headers .= "\n\n--$boundary2--\n";
//--------------------------------------------------------------------------
if (mail($to, $subject, $message, $headers))
return true;
else
return false;
}
