Created
June 18, 2014 21:03
-
-
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.
This file contains hidden or 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
<?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 = "[email protected]"; | |
$mail->subject = "CSV Output for that query you asked for"; | |
$mail->hash = md5(uniqid()); | |
$mail->headers = array( | |
"From: [email protected]", | |
"Reply-To: [email protected]", // 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