Laravel: attach multiple PDFs to email - laravel

Following is a code to send a PDF with email:
$pdf = PDF::loadHTML($str_html)->setPaper('a4', 'portrait');
Mail::send('emails.mail', $data, function($message) use ($data,$pdf){
$message->from('noreply#...');
$message->to('...');
$message->subject('test test');
//Attach PDF doc
$message->attachData($pdf->output(),'invoice.pdf');
});
But my requirement is to send multiple PDFs with email, how can I do this?

$attachments = [
// first attachment
'/path/to/file1',
// second attachment
'/path/to/file2',
...
];
$pdf = PDF::loadHTML($str_html)->setPaper('a4', 'portrait');
Mail::send('emails.mail', $data, function($message) use ($data,$pdf){
$message->from('noreply#...');
$message->to('...');
$message->subject('test test');
//Attach PDF doc
foreach($attachments as $filePath){
$message->attach($filePath);
}
});

taibur rahman provides an answer in comment, new PDFs variables must be added in "use", then code will be correct.
Complete Code:
$pdf = PDF::loadHTML($str_html)->setPaper('a4', 'portrait');
$pdf2 = PDF::loadHTML($str_html2)->setPaper('a4', 'portrait');
Mail::send('emails.mail', $data, function($message) use ($data, $pdf, $pdf2){
$message->from('...#...');
$message->to(...#...);
$message->subject('test test');
$message->attachData($pdf->output(),'test.pdf');
$message->attachData($pdf2->output(),'test2.pdf');
});

Related

Use Laravel to Download table as xls

I want to download the data of table in excel file
I have an application in Laravel and I want to add a functionality that download user data in .xls format
Route::get('users/download', function(){
$table = App\User::all();
$filename = "User.csv";
$handle = fopen($filename, 'w+');
fputcsv($handle, array('ID', 'User Name'));
foreach($table as $row) {
fputcsv($handle, array($row['id'], $row['username']));
}
fclose($handle);
$headers = array(
'Content-Type' => 'text/csv'
);
return Response::download($filename, 'User.csv', $headers);
});
This code works fine for .csv files what changes are required for .xls file?
Take a look at Laravel Excel: https://github.com/Maatwebsite/Laravel-Excel
Its very easy to use with Laravel.

Send CSV file in response through REST API

I need to send a CSV file through rest api.
I am using reactjs for front end development and constructing backend apis with Laravel.
I am confused with how to send a CSV file through api response ?
Can anyone help me?
this function will download csv file
public function downloadCSV(Request $request){
$table = User::orderBy('created_at','desc')->with('user')->get();
$filename = "users.csv";
$handle = fopen($filename, 'w+');
fputcsv($handle, array('user_name','user_email','country','state','address','zip_code','city'));
foreach($table as $row) {
fputcsv($handle, array(
$row['user_name'],
$row['user_email'],
$row['country'],
$row['state'],
$row['address'],
$row['zip_code'],
$row['city']
));
}
fclose($handle);
$headers = array('Content-Type' => 'text/csv');
return response()->download($filename, 'users.csv', $headers);
}

Not able to save generated pdf on my remote server

I am trying to save generated pdf in custom folder but its not saving. I want to pdf to send as attachment in email
Here is my code generate and save pdf
public function email($timestamp=0, $load_id=0, $type=0){
$this->load->library('tcpdf/Pdf');
$pdf = new Pdf('P', 'mm', 'LETTER', true, 'UTF-8', false);
$pdf->SetTitle('Document');
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetHeaderMargin(10);
$pdf->SetLeftMargin(10);
$pdf->SetRightMargin(10);
$pdf->SetTopMargin(10);
$pdf->SetAutoPageBreak(true, 25);
$pdf->SetAuthor('Author');
$pdf->SetDisplayMode('real', 'default');
$pdf->Write(5, 'Cal Sierra Load Document'); // add a page
$pdf->AddPage();
// $carriers = $this->admin_model->getCarriers(array(), array(), 0,0,1,"","","",1);
$load=$this->admin_model->getLoad($load_id);
$pickupDrops=$this->admin_model->getPickupDrops(0,0,1,0,$load_id);
$loadPickups=array();
$loadDrops=array();
if(!empty($pickupDrops)){
foreach($pickupDrops as $row){
if($row['type']==1)
$loadPickups[]=$row;
else
$loadDrops[]=$row;
}
}
$data['load'] = $load;
$data['loadPickups'] = $loadPickups;
$data['loadDrops'] = $loadDrops;
// $data['carriers'] = $carriers;
$data['settings'] = $this->settings_model->getSettingsFile();
$data['currentTime'] = $timestamp;
// echo "<pre>";
// print_r($data);
// exit();
switch ($type) {
case 1:
$html = $this->load->view('documents/doc1', $data, true);
break;
case 2:
$html = $this->load->view('documents/doc2', $data, true);
break;
case 3:
$html = $this->load->view('documents/doc3', $data, true);
break;
default:
}
$pdf->Output('custom'.'Document.pdf', 'F');
$this->Output("custom");
exit();
}
I am not sure where put my folder to pdf i am also adding my folder layout picture https://i.stack.imgur.com/tUadw.png
Try adding a more complete path to the output function. Something like:
$pdf->output(FCPATH . "my/directory/path/" . "pdfName.pdf", 'F');

Problems in parsing variable within body stored in database

I have an issue in parsing variable.
I have dynamic email template for all types of email like registration,activation and so on
Suppose i want to send feedback email and i have email template for feedback stored in database.
In database it is stored as Name:{{ $name }}
But when i sent email it is sending Name:{{ $name }} instead of actual name like Name:john
Following is my code:
$name = $request->get('name');
$address = $request->get('address');
$phone = $request->get('phone');
$emailaddress = $request->get('email_address');
$feedbacktext = $request->get`enter code here`('message');
Mail::send('lugmety.frontend.partials.contactUsEmail',
[ 'name' => $name,
],
function ($mail)
use ($address, $name,$phone,$emailaddress,$feedbacktext) {
$mail->to('anandshrestha57#gmail.com')->subject('FeedBack Form')->from($emailaddress,$name);
});
Here is my view which contains email template obtained from database.
<?php echo \App\EmailTemplate::where('slug','contact-us')->first()->body; ?>
Thanks for help.
private function parsed_content($email_template, array $args = array()){
$generated = \Blade::compileString($email_template);
ob_start() and extract($args, EXTR_SKIP);
try{
eval('?>'.$generated);
}catch (\Exception $e){
b_get_clean(); throw $e;
}
$content = ob_get_clean();
return $content;
}
And for parsing variable in email template stored in database:
$emailTemplate = EmailTemplate::where('slug','contact-us')->first();
$email_body = $this->parsed_content($emailTemplate, array(
'name' => $name,
'address' => $address,
'phone' => $phone,
'emailaddress' => $emailaddress,
'feedbacktext'=>$feedbacktext
));
$body = json_decode($email_body,true)['body'];
And for sending email:
Mail::send([],[],
function ($mail)
use ($body,$address, $name,$phone,$emailaddress,$feedbacktext) {
$mail->to('anandshrestha57#gmail.com')->subject('FeedBack Form')->from($emailaddress,$name)
->setBody($body,'text/html');
});
So no need of making every view. Source:#Is there any way to compile a blade template from a string?
Add a function in EmailTemplate Model
//$value is $EmailTemplate->body value
public function getBodyAttribute($value)
{
//get value name by request function
$name = request()->get('name');
//do your regex code to replace {{ name }} from $name in $value and update.....
//finaly return $value;
return $value;
}

Codeigniter how to html template for emails

I'm using below code to send email from my codeigniter based website's contact form, to do that i'm using below codes in my controller,
$entrydata['name']= $this->input->post('name');
$entrydata['email']= $this->input->post('email');
$entrydata['phone']= $this->input->post('phone');
$entrydata['message']= $this->input->post('message');$msg = 'Email has sent successfully';
$data['reset'] = TRUE;
$this->load->library('email');
$this->email->from(set_value('email'), set_value('name'));
$this->email->to('my#webs.com');
$this->email->subject("Get a quote enquiry");
$all = 'Name:' . set_value('name') ."\n". 'Email :' .' '. set_value('email') ."\n".'Phone :' .' '. set_value('phone') ."\n".'Message :' .' '. set_value('message'); $this->email->message($all);
$s=$this->email->send();
$data['message'] = $msg;
Did anyone know how to add custom email template that'll hold my conact form informations?
This is an example which i have done
$data['map_to']=$this->input->post('map_to');
$event=$this->db->query("query");
if($event->num_rows()>0)
{
$data['event']=$event->row();
$data['map_from']=$event->row()->address2;
}
else
{
$data['event']=NULL;
}
$data['sender_mail'] = 'xx#xx.org';
$this->load->library('email');
$config = array (
'mailtype' => 'html',
'charset' => 'utf-8',
'priority' => '1'
);
$this->email->initialize($config);
$this->email->from($data['sender_mail'], 'xxxx');
$this->email->to($mail);
$this->email->subject('Map Location');
$message=$this->load->view('map_mail_format',$data,TRUE);
$this->email->message($message);
$this->email->send();
Here i am loading a view page called map_mail_format and passing values to that view page ($data) then assign that view page to a variable then send mail with that message
first you need to initialize config as
$config['charset'] = 'utf-8';
$config['wordwrap'] = TRUE;
$config['mailtype'] = 'html';
$this->email->initialize($config);
after you load email library and then you can store your email view to a variable and mail it
$mailbody = $this->load->view('myfile', $data, true);
You may try this
$this->load->helper(array('email'));
$this->load->library(array('email'));
$this->email->set_mailtype("html");

Resources