Click here to Skip to main content
15,919,931 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

Using php i am trying to email database table data in csv format in attachment below is the code which i have tried but i am getting blank csv file in attachment.

What I have tried:


$hostname = "localhost";
$username = "root";
$password = "";
$database = "owner";
$conn = mysql_connect($hostname, $username, $password) or die(mysql_error());
$db_selected = mysql_select_db($database, $conn);

$sql = mysql_query("SELECT * FROM bucket");
foreach($row as $name =>$value)
foreach($row as $name =>$value)
$my_file = $filename.'.csv';
$path = "temp/";
$from_name = "PTP database";
$from_mail = "";
$mailto = "";
$subject = "This is a mail with attachment.";
$message = "Hi,\r\n do you got attachment?\r\n\r\Hara";
$file = $path.$my_file;
    $file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
$content = chunk_split(base64_encode($content));

$uid = md5(uniqid(time()));

$name = basename($file);

 $header = "From: ".$from_name." <".$from_mail.">\r\n";

$header .= "Reply-To: ".$replyto."\r\n";
    $header .= "MIME-Version: 1.0\r\n";

 $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";

$header .= "This is a multi-part message in MIME format.\r\n";

$header .= "--".$uid."\r\n";

$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";

$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";

$header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";

$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here

$header .= "Content-Transfer-Encoding: base64\r\n";

$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";

$header .= "--".$uid."--";

if (mail($mailto, $subject, $message, $header)){
                echo "Mail send";
} else{
                echo "can not send mail";
Updated 29-Apr-19 0:37am
Richard MacCutchan 29-Apr-19 4:09am    
Have you checked that your code is actually generating the correct lines at each loop?

1 solution

Immediately I can see that you're writing to one path (ptp/filename.csv) but then attempting to read the content back out again at a different path (temp/filename.csv).
Share this answer
Richard MacCutchan 29-Apr-19 7:07am    
Well spotted, I missed that.
sapnawat 29-Apr-19 7:30am    
Hi Chris & Richard, Thanks for the reply,

I have changed the read content path to (ptp/filename.csv) but getting the blank csv file again.
ZurdoDev 29-Apr-19 13:43pm    
Then debug your code. It's that simple.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900