I don't know why I'm having so much trouble with this. Since I know very little about e-mail headers, I Googled how to attach files to e-mails and copied and pasted code. When this didn't work out as planned, I tried several other sources, but to no avail. I didn't think this would be so complicated.
Basically, I have a script that converts a MySQL table to a CSV file and attempts to attach its contents in an e-mail that is dispatched via CRON as a weekly digest.
I know the conversion from the table to CSV doesn't have any errors--it outputs just as expected. The e-mail is dispatched, but I receive an e-mail with no attachment and the message body reads five or six random characters, like so: "Ù Ø Ù".
Any idea what I'm doing wrong? Here's the code:
<?php
require "db.php";
$q = mysql_query("SELECT * FROM `users`;");
$csv = "";
while($row = mysql_fetch_assoc($q))
{
$id = $row["id"];
$row = str_replace("\"", "\"\"", $row);
$csv .= $row["id"].", \"".$row["name"]."\", \"".$row["title"]."\", \"".$row["company"]."\", \"".$row["office"]."\", \"".$row["mobile"]."\", \"".
$row["streetaddress"]."\", \"".$row["email"]."\", \"".$row["licensees"]."\", \"".$row["comments"]."\", \"".date("D, M d, Y @ h:i A", $row["timestamp"])."\"\r\n";
}
echo "<pre>".$csv."</pre>";
$fn = "Digest ".date("Y.m.d H-i-s").".csv";
$type = "application/excel";
$to = "(Me) <(myemail@address)>";
$headers = "From: (my company) <noreply@(mydomain.com)>";
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n".
"Content-Type: multipart/mixed;\n".
" boundary=\"{$mime_boundary}\"";
$email_message .= "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".
"Attached is a spreadsheet containing the contents of the users table of (my company).\n\n";
$data = chunk_split(base64_encode($csv));
$email_message .= "--{$mime_boundary}\n".
"Content-Type: {$type};\n".
" name=\"{$fn}\"\n".
"Content-Transfer-Encoding: base64\n\n".
$data."\n\n".
"--{$mime_boundary}--\n";
if(mail($to, "Weekly digest from (my company)", $message, $headers))
echo "Mail sent.";
else
echo "Mail not sent.";
?>
Help is much appreciated. Thank you!