How to attach a .csv (generated by php) via using SendGrid? - php

I leave a simple text for fast reading.
I'm trying to figure out how to send a csv file via sendgrid, csv is used with array, it's
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
It's not a real file from server, simply to create file and export data to users.
The problem is... addAttachment or setAttachment returned some errors, they requiere where to find a file from path or directory.
How to attach a file without requesting an existing file from directory via sendgrid?
EDIT:
//Function to generate csv file
private function array2csv($array) {
if (count($array) == 0) {
return null;
}
$lista = $array;
ob_start();
$fp = fopen('php://output', 'w');
foreach ($array as $campos) {
fputcsv($fp, $campos);
}
fclose($fp);
return ob_get_clean();
}
//Call a function to send csv file
public function sendCSVFile(){
$data = $this->reqProducts();
//prepareParams is csv templating and formatting function.
$products = $this->prepareParams($data);
$products = $this->array2csv($products);
$body = "Hello, you have an attached file."
$email = new SendGrid\Email();
$email
->addTo('foo#bar.com')
->setFrom('me#bar.com')
->setSubject($body)
->setText($body)
->setHtml('<strong>Hello World!</strong>')
->addAttachment($products);
}
Error output is:

Related

Email attachement in Laravel

I am working on Laravel file attachment. I have to send CSV file as attachment in mail without downloading the file to my server. When I click the submit button it didnot send email with file attachment.
My Controller:
$data["email"] = $request->recipient_email;
$data["subject"] = 'Cashup Report for '. $venue->name;
$data["bodyMessage"] = $venue->name.' from '.$start.' to '.$end ;
$excel_file = Excel::create(uniqid().'Cashups', function($excel) use($transactions,$start,$end,$venue) {
$excel->sheet('New sheet', function($sheet) use($transactions,$start,$end,$venue) {
$sheet->loadView('excel.cashups', array('transactions' => $transactions, 'start'=> $start, 'end' => $end, 'venue' => $venue));
});
});
//Feedback mail to client
Mail::send('emails.cashups_report', $data, function($message) use ($data,$excel_file){
$message->from(config('mail.from.address'));
$message->to($data["email"]);
$message->subject($data["subject"]);
//Attach PDF doc
$message->attachData($excel_file,'cashups-report.xlsx');
});
I dont know where i am going wrong. I have already put much time over this but didn't find any solution.
Any guidence in this regards will be highly appreciated. Thanks
You can achieve your goal using the code below. I tried my level best to explain everything in the comments of the code.
//function to generate the csv to be attached in your email
public function createCSV()
{
$myData = MyModel::where(myConditions)->get(['col1','col2','col3']);
header('Content-Type: text/csv; charset=utf-8');
//header without attachment; this instructs the function not to download the csv
header("Content-Disposition: filename=myCsvFile.csv");
//Temporarily open a file and store it in a temp file using php's wrapper function php://temp. You can also use php://memory but I prefered temp.
$Myfile = fopen('php://temp', 'w');
//state headers / column names for the csv
$headers = array('col_name1','col_name2','col_name3');
//write the headers to the opened file
fputcsv($Myfile, $headers);
//parse data to get rows
foreach ($myData as $data) {
$row=array(
$data->col1,
$data->col2,
$data->col3,
);
//write the data to the opened file;
fputcsv($Myfile, $row);
}
//rewind is a php function that sets the pointer at begining of the file to handle the streams of data
rewind($Myfile);
//stream the data to Myfile
return stream_get_contents($Myfile);
}
second function: this sends the email to receipients with the csv attached
public function sendEmail()
{
Mail::send('path_to_your_view.My_view', array(''),
function($message){
$message->to(explode(',', env('EMAILS')))
->subject('Email Subject')
->attachData($this->createCSV(), "MyfileName.csv");
});
}
/*......¯\_(ツ)_/¯......
It works on my computer*/
Best of luck! :)

How to create formated Excel lists from mySQL database?

I use a mySQL database and have to create some lists in Excel format (xlsx). The Excel sheets must be formated. For csv export I use phpExcel (I know, it is obsolete but still working).
Which add on do I need to create formated Excel sheets from my mySQL database. I use php to create the frontend.
Thanks,
Markus
This is just a copy of the function i use. It just launches the function when a specific $_GET isset. The function creates a xlsx file. If you want to export the file as .csv you can just change the file extension and edit text/xlsm to text/csv
$gg = $db->prepare("SELECT * FROM beta_mails ORDER BY created DESC");
$gg->execute();
$ggg = $gg->get_result();
$gg->store_result();
while ($row = $ggg->fetch_assoc()) {
$data[] = $row;
}
function getprelaunchCSV(){
global $data;
header('Content-Type: text/xlsx; charset=utf-8');
header('Content-Disposition: attachment; filename=data.xlsx');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('ID', 'EMAIL', 'OPRETTET'));
foreach ($data as $rowCSV){
fputcsv($output, [$rowCSV["id"], decrypt($rowCSV["email"]), $rowCSV["created"]]);
}
fclose($output);
die();
}
if (isset($_GET["getlist"]) && $_GET["getlist"] == "1") {
echo getprelaunchcsv();
header("Location:admin?success=1");
}

Output to CSV generating errors

I don't have a lot of experience with using the fputcsv function.
I'm trying to make a function, by which an admin can download a file with all the user information.
The CSV should be generated in this way :
Serial Number Username Email etc etc
And then the records from a query.
I have this function which I'm using to generate the csv file :
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
// rewrind the "file" with the csv lines
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachement; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
}
And then I call the function:
<?php
include 'inc/inc.functions.php';
include 'dbconnector.php';
$query="SELECT * from users order by email LIMIT 0,30";
$result=mysql_query($query,$db) or die(mysql_error($db));
$array=mysql_fetch_array($result);
foreach($array as $arr)
{
array_to_csv_download($arr,"records.csv",":");
}
?>
The CSV generated displays: Warning, Invalid argument supplied for foreach.
What should I do to display in the way I require?
UPDATE
http://i.imgur.com/2xH0gT1.png
You're currently calling your function for a single row in the database, rather than for the entire result set. The following should use your function correctly:
$query = "SELECT * from users order by email LIMIT 0,30";
$result = mysql_query($query,$db) or die(mysql_error($db));
$array = array();
# Headers
$array[] = array("Serial Number","Username","Email","etc etc");
while($row = mysql_fetch_row($result)) {
$array[] = $row;
}
array_to_csv_download($array,"records.csv",":");

Issue creating CSV in PHP MySQL

I have to run a pairing algorithm for a game and when the pairing is done, I display the pairing on HTML and create a csv file as well. Right now, once I am done with pairing, I create a multidimensional array to store the specific value and then pass it to the function in same php file to generate the csv file. However, doing this outputs the entire page code i.e. html and php code to the .csv file. Here is the code:
function performPairing()
{
....
$count=0;
$resultArray[][] = array();
while ($currrow = #mysql_fetch_row($result))
{
$playerone = $currrow;
$playertwo = #mysql_fetch_row($result);
$resultArray[$count][] = $playerone[1];
$resultArray[$count][] = $playerone[0];
$resultArray[$count][] = $playertwo[1];
$resultArray[$count][] = $playertwo[0];
$count++;
updateforeachrow($playerone, $playertwo);
}
generateDocument($resultArray, $count);
}
function generateDocument($resultArray, $count)
{
$output = fopen('php://temp/maxmemory'.(5*1024*1024), 'r+');
$columns = array('Player One Col1', 'Player One Col2', 'Player Two Col1', 'Player Two Col2');
fputcsv($output, $columns);
for ($index=0 ; $index <=$count; $index++)
{
fputcsv($output, $resultArray[$index]);
}
rewind($output);
$export = stream_get_contents($output);
fclose($output);
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename = "export.csv"');
echo $export;
}
However doing this outputs the entire html code to csv rather than specific rows. Can anyone please help me on this?
. make string
. output string to file
. send header with (is this allowed this way?)
use file_put_contents ( filename, str ), and than send it with headers.
Make code simpler :)

CSV file_get_contents sending PHP

I'm trying to send a .CSV file with PHP. The file is written to disk before it's sent but when I try to attach the file with file_get_contents(); the structure of the .CSV isn't preseved yet when try and send the file that's created before it's sent I get a resource id (#183) so how can i attach a file which the user can open as a .CSV file? I've made sure the mime type and headers are correct
EDIT
if(!file_exists(_PS_ORDERS_DIR_.$orderDate.'/'.$file_name.'.csv'))
{
if($file = fopen (_PS_ORDERS_DIR_.$orderDate.'/'.$file_name.'.csv', 'x+'))
{
foreach ($list as $fields)
{
fputcsv($file, $fields);
}
$attachment['mime'] = 'application/vnd.ms-excel';
$attachment['content'] = file_get_contents(_PS_ORDERS_DIR_.$orderDate.'/'.$file_name.'.csv');
$attachment['name'] = $order.'order';
Mail::Send(1, 'order_conf', 'Order CSV Attachment', $success, 'dan.farr#gmail.com', CakeToppers, NULL, NULL, $attachment);
return true;
}
If you are using Swift Mailer, there is no need for file_get_contents(), you can just attach the file directly.
From the Swift Mailer documentation:
//Create the attachment
// * Note that you can technically leave the content-type parameter out
$attachment = Swift_Attachment::fromPath('/path/to/image.jpg', 'image/jpeg');
//Attach it to the message
$message->attach($attachment);
So for you that would be:
$attachment = Swift_Attachment::fromPath(_PS_ORDERS_DIR_.$orderDate.'/'.$file_name.'.csv', 'application/vnd.ms-excel');
//Attach it to the message
$message->attach($attachment);

Categories