Mr.Z Mr.Z - 16 days ago 5
PHP Question

Send pdf in Email Without Saving it on Server Using Codeigniter

I have been trying to send email with attachment of

pdf
produced by
MPDF
library in codeigniter from my view, I have successfully converted my file to
PDF
or i think i did, but i cannot find any way to attach that file to email using given functionality in CodeIgniter.

In Documentation of CodeIgnitor a confusing and incomplete description of
attach
function is suggesting this:


$this->email->attach($buffer, 'attachment', 'report.pdf',
'application/pdf');


Where
$buffer
is string
report.pdf
will be the fileName where of attachment with email,

Now my concern here is can i attach my generated view something like this:

ini_set('memory_limit', '20M');
// load library
$this->load->library('pdf');
$pdf = $this->pdf->load();

// boost the memory limit if it's low ;)
$html = $this->load->view('reports/someReport', array('var' => 123), true);
// render the view into HTML
$pdf->WriteHTML($html);
$this->email->attach($pdf->Output('', 'S'), 'attachment', 'report.pdf', 'application/pdf'); // is this okay or something is wrong here ?


How can i attach it successfully with email and send it

Answer

First, you can save PDF file in your project folder like attach. And then this pdf location set email attachment. Like bellow : :

<?php
ini_set('memory_limit', '20M');
// load library
$this->load->library('pdf');
$pdf = $this->pdf->load();

// boost the memory limit if it's low ;)
$html = $this->load->view('reports/someReport', array('var' => 123), true);
// render the view into HTML

$pdfFilePath = FCPATH . "attach/pdf_name.pdf";
$pdf->WriteHTML($html);
$pdf->Output($pdfFilePath, "F");

$result = $this->email
            ->from('example@test.com', 'From name')
            ->to('test@test.com')
            ->subject($subject)
            ->message($body)
            ->attach($pdfFilePath)
            ->send();
$this->email->clear($pdfFilePath);
if($result) {
    echo "Send";
    unlink($pdfFilePath); //for delete generated pdf file. 
}
?>