Sometimes we don't just want data transferred to the computer, but we want to automatically send it to a specific email address (e.g., daily sales report or list of new subscribers). Below is a script that converts data from the database to CSV and sends it as an attachment.
How does the script work?
Instead of saving the file to disk, PHP creates it in memory, encodes it in Base64 format (which isstandard for email attachments), and attaches it to the message with appropriate boundaries.
<?php
// Database credentials
$server = "localhost";
$username = "root";
$password = "";
$database = "your_database_name";
$connection = new mysqli($server, $username, $password, $database);
// 1. Prepare CSV content in variable
$csv_content = "ID,Name,Link\n"; // Header
$sql = "SELECT id, name, link FROM names";
$result = $connection->query($sql);
while ($row = $result->fetch_assoc()) {
$csv_content .= $row['id'] . ',"' . $row['name'] . '","' . $row['link'] . '"\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. Headers for email with 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 .= "Attached we send you exported data in CSV format.\r\n\r\n";
// 5. Adding 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
if (mail($to, $subject, $message, $headers)) {
echo "Email with CSV attachment was successfully sent!";
} else {
echo "Error sending email.";
}
$connection->close();
?>