Skip to content

Instantly share code, notes, and snippets.

@jdrydn
Created June 18, 2014 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdrydn/db0b076e8a3355e324e1 to your computer and use it in GitHub Desktop.
Save jdrydn/db0b076e8a3355e324e1 to your computer and use it in GitHub Desktop.
A simple script to email the results of a query as a CSV.
<?php
$query = 'SELECT id, column1, column2, column3 FROM ImportantTable WHERE something LIKE "SomethingElse%";';
exec("mysql -h 123.456.789.012 -u SomeImportantUser -p'P4ssw0rd!' BigImportantDatabase -e '$query' | sed 's/\t/,/g' > ".__DIR__."/output.csv");
$mail = new stdClass;
$mail->to = "james@jdrydn.com";
$mail->subject = "CSV Output for that query you asked for";
$mail->hash = md5(uniqid());
$mail->headers = array(
"From: someaddress@mycleversever.local",
"Reply-To: james@jdrydn.com", // So that a human will read the reply!
"Content-Type: multipart/mixed; boundary=\"PHP-mixed-".$mail->hash."\""
);
$mail->attachment = chunk_split(base64_encode(file_get_contents(__DIR__."/output.csv")));
ob_start();
?>
--PHP-mixed-<?php echo $mail->hash;?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $mail->hash;?>"
Hello there!
Here is the weekly output for that query.
With love,
A robot
--PHP-mixed-<?php echo $mail->hash;?>
Content-Type: text/csv; name="importantfilename.csv"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $mail->attachment; ?>
--PHP-mixed-<?php echo $mail->hash;?>--
<?php
$mail->message = ob_get_clean();
$mail->sent = @mail($mail->to, $mail->subject, $mail->message, implode("\r\n", $mail->headers));
echo ($mail->sent ? "Mail sent." : "Mail failed"), PHP_EOL;
unlink(__DIR__."/output.csv");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment