Sometimes you don't just want to download data; you might want to automatically send it to a specific email address (e.g., a daily sales report or a list of new subscribers). Below is a script that converts database data into CSV format and sends it as an email attachment.
How the Script Works
Instead of saving the file to the disk, PHP generates it in memory, encodes it into Base64 format (the standard for email attachments), and attaches it to the message using appropriate MIME boundaries.
<?php
// Database credentials
$server = "localhost";
$user = "root";
$pass = "";
$db = "your_database_name";
$conn = new mysqli($server, $user, $pass, $db);
// 1. Prepare CSV content into a variable
$csv_content = "ID,Name,Link\n"; // Header
$sql = "SELECT id, ime, povezava FROM imena";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
$csv_content .= $row['id'] . ',"' . $row['ime'] . '","' . $row['povezava'] . ""\n";
}
// 2. Email settings
$to = "recipient@domain.com";
$subject = "Daily Data Export";
$filename = "data_" . date("Y-m-d") . ".csv";
$encoded_content = chunk_split(base64_encode($csv_content));
$boundary = md5(time());
// 3. Email headers for attachment
$headers = "From: system@your-domain.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary="" . $boundary . ""\r\n";
// 4. Message body
$message = "--" . $boundary . "\r\n";
$message .= "Content-Type: text/plain; charset="utf-8"\r\n";
$message .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
$message .= "Please find the exported data in CSV format attached.\r\n\r\n";
// 5. Adding the attachment
$message .= "--" . $boundary . "\r\n";
$message .= "Content-Type: text/csv; name="" . $filename . ""\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment; filename="" . $filename . ""\r\n\r\n";
$message .= $encoded_content . "\r\n";
$message .= "--" . $boundary . "--";
// Sending the mail
if (mail($to, $subject, $message, $headers)) {
echo "Email with CSV attachment sent successfully!";
} else {
echo "Error sending email.";
}
$conn->close();
?>