Created
January 28, 2018 15:36
-
-
Save waqashassan98/a9d001ed9a0739f34ab01f680b6e6bbc to your computer and use it in GitHub Desktop.
Dynamically create CSV and send as attachment in emails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function send_csv_mail($data, $body, $to = 'email@example.com', $subject = 'Website Report', $from = 'waqashassan98@gmail.com') { | |
if (!$fp = fopen('php://temp', 'w+')) echo "unable to create csv"; | |
foreach ($data as $row) | |
{ | |
fputcsv($fp, $row); | |
} | |
rewind($fp); | |
$csvData = stream_get_contents($fp); | |
// Make the attachment | |
$attachment = chunk_split(base64_encode($csvData)); | |
$filename = "booking_report_".date('m-d-Y').".csv"; | |
$eol = PHP_EOL; | |
$uid = md5(uniqid(time())); | |
// Basic headers | |
$header = "From: ".$from." <".$from.">".$eol; | |
$header .= "Reply-To: ".$from.$eol; | |
$header .= "MIME-Version: 1.0\r\n"; | |
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\""; | |
// Put everything else in $message | |
$message = "--".$uid.$eol; | |
$message .= "Content-Type: text/html; charset=ISO-8859-1".$eol; | |
$message .= "Content-Transfer-Encoding: 8bit".$eol.$eol; | |
$message .= $body.$eol; | |
$message .= "--".$uid.$eol; | |
$message .= "Content-Type: application/csv; name=\"".$filename."\"".$eol; | |
$message .= "Content-Transfer-Encoding: base64".$eol; | |
$message .= "Content-Disposition: attachment; filename=\"".$filename."\"".$eol; | |
$message .= $attachment.$eol; | |
$message .= "--".$uid."--"; | |
if (mail($to, $subject, $message, $header)) | |
{ | |
return "mail_success"; | |
} | |
else | |
{ | |
return "mail_error"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment