Emailing CSV file with PHP - php

I have extracted data from my database and displayed it on a webpage in table format. I provided a link on this page which allows the user to download this data as a CSV file. This works correctly so far and when the user follows the link beneath the displayed data it allows them to save it.
It also sends an email with the CSV as an attachment. However currectly the CSV in the attachment is blank and I dont know why.
All i want is for the data from the database which is placed into a downloadable CSV to also go into the attached CSV and I cant do it.
Could someone help me?
Here is the code I have so far:
// Create CSV file
fputcsv($output, array('Name', 'Branch', 'Website','Company', 'Question1', 'Question2', 'Question3', 'Question4', 'Question5'));
$mysql_connection = db_connect_enhanced('*******','******','******','******');
$query='SELECT * FROM ****.****';
$surveys = db_query_into_array_enhanced($mysql_connection, $query);
$count = count($surveys);
$data = array();
for($i=0; $i<=$count; $i++){
$data[] = array($surveys[$i]['FeedbackName'], $surveys[$i]['BranchName'], $surveys[$i]['FeedbackWebsite'], $surveys[$i]['FeedbackCompany'], $surveys[$i]['Question1'], $surveys[$i]['Question2'], $surveys[$i]['Question3'], $surveys[$i]['Question4'], $surveys[$i]['Question5']);
}
foreach( $data as $row )
{
fputcsv($output, $row, ',', '"');
}
$encoded = chunk_split(base64_encode($data));
// create the email and send it off
$subject = "File you requested from RRWH.com";
$from = "***************";
$headers = 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-Type: multipart/mixed;
boundary="----=_NextPart_001_0011_1234ABCD.4321FDAC"' . "\n";
$message = '
This is a multi-part message in MIME format.
------=_NextPart_001_0011_1234ABCD.4321FDAC
Content-Type: text/plain;
charset="us-ascii"
Content-Transfer-Encoding: 7bit
Hello
We have attached for you the PHP script that you requested from http://rrwh.com/scripts.php
as a zip file.
Regards
------=_NextPart_001_0011_1234ABCD.4321FDAC
Content-Type: application/octet-stream; name="';
$message .= "surveys.csv";
$message .= '"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="';
$message .= "surveys.csv";
$message .= '"
';
$message .= "$encoded";
$message .= '
------=_NextPart_001_0011_1234ABCD.4321FDAC--
';
mail("*************", $subject, $message, $headers, "-f$from");
fclose($output);
It feels like I am so close but I just cant see the answer :(

Change this line:
$message .= "$encoded";
With this one:
$message .= $encoded;

This is only a "SUGGESTIVE" answer:
Here is what I use to attach files and it works for me and it may help you to "BASE" yourself with the problem you're having.
$file_path = "/path_to_your/$file_name";
$file_path_name = "$file_name"; // this file name will be used at receiver end
$file = fopen($file_path,'rb');
$data = fread($file,filesize($file_path));
fclose($file);
$rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message .= "\n\n";
$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$file_path_type};\n" .
" name=\"{$file_path_name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$file_path_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data .= "\n\n" .
"--{$mime_boundary}--\n";

Related

Attachment in PHP showing 0KB

I am trying to send files as attachment through php mail function. My code is sending the files but it is showing size 0KB. I already google it but didn't found a solution. Please help me.
HTML:
<form method="post" action="code.php" enctype="multipart/form-data">
<input type="file" name="file[]" multiple="multiple" />
<button type="submit">Submit</button>
</form>
PHP:
<?php
foreach ($_FILES['file']['name'] as $filename){
$files[] = $filename; // create array of terms
}
// email fields: to, from, subject, and so on
$to = "receiver_email_here";
$from = "sender_email_here";
$subject ="My subject";
$message = "My message";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
mail($to, $subject, $message, $headers);
?>
I think I am doing something wrong in this part but I am not sure.
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
Thanks
You are trying to open $_FILES['file']['name'], but the name field contains the name of the original file, not the path to the file on the server. To access the file on the server, use
$_FILES['file']['tmp_name']
Also to make sure that the file was uploaded correctly, use
$_FILES['file']['error'] == UPLOAD_ERR_OK

Creating CSV file in PHP with Japanese characters and emailing, characters getting converted to?

I have a page that when visited performs a SQL query and creates a CSV with the results and then emails the results to me.
However the japanese characters from the DB aren't being encoded properly and the CSV file i receive just has ? in place of each of the Japanese characters.
I have tried changing the "Content-Encoding", "Content-Transfer-Encoding", "Content-Type" to get a setting that works but no matter what I try i still only see ?? where there should be 東京
This is my code that generates the CSV on the fly and sends it.
$headers = "From: ".$email_from;
$random_hash = md5(date('r', time()));
$mime_boundary = "==Multipart_Boundary_x{$random_hash}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$email_message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: UTF-8\n\n" .
$this->email_html_msg . "\n\n";
$files_attached_cnt = 0;
foreach ($this->arr_file_data AS $file_data) {
$csv_file = $this->buildCSV($file_data, $mysqli);
if ($csv_file != "") {
$files_attached_cnt += 1;
$data = $csv_file;
$email_message .= "--{$mime_boundary}\n";
$email_message .= "Content-Type: application/csv; charset=\"UTF-8\"\n" .
" name=\"{$file_data['csv_file_name']}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$file_data['csv_file_name']}\"\n" .
"Content-Transfer-Encoding: UTF-8\n" .
"Content-Encoding: UTF-8\n\n" .
$data . "\n\n";
}
}
$email_message .= "--{$mime_boundary}--\n";
$this->arr_file_data = array();
if ($this->debugFlag) {
echo "FINISHED.";
}
Do I need to change my code completely or is there an encoding setting that would work in this instance?
Thanks in advance
found the answer was to set my sql query charset to utf8 before i actually started the query,
I added this
$mysqli->set_charset('utf8');
right after specifying the mysqli object.

php email attachment sends an empty file

I'm trying to send an attachment via email but, even though the right file is saved in the server, the one attached to the email is empty (0 kb).
I'm using gmail to send the emails.
Here is the relevant part of my code:
if (empty($error)) {
//boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x$semi_randx";
//tell the headers about the boundary
$header .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"$mime_boundary\"";
//define the first part of the email, which is the text part
$message = "\r\n" . "--$mime_boundary\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\r\n" ;
//build the body of the 1st part of the email
$content_body = "
Email del formulario de contacto en ".home_url().": <br />
//whatever
";
$message .= $content_body . "\r\n";
$message .= "--$mime_boundary\n";
//define the second part of the email, which is the atachments
//if a file has been uploaded
if (!empty($_FILES['cv']['name'])){
// Open the file for a binary read
$file = fopen($temp_name,'rb');
// Read the file content into a variable
$data = fread($file,filesize($temp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
// Actually build the second part of the email
$message .= "Content-Type: \"application/octet-stream\";\r\n name=\"" . $file_name . "\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-Disposition: attachment;\r\n filename=\"" . $file . "\"\r\n\r\n";
$message .= $data; //The base64 encoded message
$message .= "\n";
$message .= "--$mime_boundary--\n";
}
//send th email
mail( $receive_email, "Email del formulario de contacto en web", $message, $header);
$msg = $succesful_text;
}
My guess is that I'm doing something wrong here:
$message .= "Content-Type: \"application/octet-stream\";\r\n name=\"" . $file_name . "\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-Disposition: attachment;\r\n filename=\"" . $file . "\"\r\n\r\n";
$message .= $data; //The base64 encoded message
$message .= "\n";
$message .= "--$mime_boundary--\n";
But I have no idea what it can be.
I know I can use a library, but I would like to see what is wrong with my code just for the sake of learning.
Any help will be highly appreciated.
Sonia
Thanks Cherry and miken32 for your replies.
Finally I figured it out.
This is what happened, in case it can help somebody else in a future.
As there was no base64 encoded data in the text message, I thought the problem might no be in the $message text but in the actual handling of the file.
// Open the file for a binary read
$file = fopen($temp_name,'rb');
// Read the file content into a variable
$data = fread($file,filesize($temp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
I realized the temp file was not being opened. I couldn't see why but I solved it by handling directly the file from the uploads folder.
Here is the fixed code:
// Open the file for a binary read
$file = fopen($server_file,'rb');
// Read the file content into a variable
$flsz=filesize($server_file);
$data = fread($file,$flsz);
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
I also had to modify the filename in the $message text, using $file_name instead of $file because $file.
$message .= "Content-Disposition: attachment;\r\n filename=\"" . $file_name . "\"\r\n\r\n";

Sending multiple word documents as attachments in PHP

I have a function to send an email with multiple word documents as attachments. Only problem is that no matter how many documents I send, only 1 shows up in the email, and also, it shows up as corrupted. The file path name is correct, I have tested this, but when I try to open the document from the email, Microsoft word complains about corrupted file. Somebody please tell me what I am doing wrong?
function mail_attachment_multiple($to, $subject, $message, $attachment, $from){//sends email as an attachment. attachment parameter is the path to file
$fileatt_type = "application/msword"; // File Type
$email_from = $from; // Who the email is from
$email_subject = $subject; // The Subject of the email
$email_txt = $message; // Message that the email has in it
$email_to = $to; // Who the email is to
$headers = "From: ".$email_from;
$msg_txt="\n\n You have recieved a new attachment message from $from";
$email_message = "";
//loop through array: $key = filename; $value = filenamePATH
foreach($attachment as $key => $value){
$fileatt_name = $key; //name of file
$fileatt_path = $value; // file path (http://www.example.com/filePath)
$file = fopen($fileatt_path,'rb');
$temp = get_headers($fileatt_path, 1);
$file_size = $temp['Content-Length'];
$data = fread($file, $file_size); //filesize($fileatt_path)
fclose($file);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$email_txt .= $msg_txt;
$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$email_txt . "\n\n";
$data[$key] = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_path}\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" ."--{$mime_boundary}--\n";
}
return #mail($email_to, $email_subject, $email_message, $headers);?>
Thanks for the help!
You should really use a mail library for this sort of thing. I highly recommend SwiftMailer.

Send CSV file attached to the email

I have an issue: i need to create csv file and send it attached to the particular emails.
Honestly i never do that so i'm quite a lammer in this matter. Can anybody tell me with what i have to start or share some links?
I think this what you are looking for, i've used it in the past works perfectly.
Hope it helps.
<?php
$cr = "\n";
$csvdata = "First Name" . ',' . "Last Name" . $cr;
$csvdata .= $txtFName . ',' . $txtLName . $cr;
$thisfile = 'file.csv';
$encoded = chunk_split(base64_encode($csvdata));
// create the email and send it off
$subject = "File you requested from RRWH.com";
$from = "scripts#rrwh.com";
$headers = 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-Type: multipart/mixed;
boundary="----=_NextPart_001_0011_1234ABCD.4321FDAC"' . "\n";
$message = '
This is a multi-part message in MIME format.
------=_NextPart_001_0011_1234ABCD.4321FDAC
Content-Type: text/plain;
charset="us-ascii"
Content-Transfer-Encoding: 7bit
Hello
We have attached for you the PHP script that you requested from http://rrwh.com/scripts.php
as a zip file.
Regards
------=_NextPart_001_0011_1234ABCD.4321FDAC
Content-Type: application/octet-stream; name="';
$message .= "$thisfile";
$message .= '"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="';
$message .= "$thisfile";
$message .= '"
';
$message .= "$encoded";
$message .= '
------=_NextPart_001_0011_1234ABCD.4321FDAC--
';
// now send the email
mail($email, $subject, $message, $headers, "-f$from");
?>
Kind regards,
Wesley.

Categories