How to send generated pdf in mail in codeingiter

To send a generated PDF file in an email using CodeIgniter, you can follow these steps:

Step 1: Generate the PDF file

You can use a library like TCPDF or DomPDF to generate the PDF file. Here's an example using TCPDF:

$pdf = new TCPDF();
$pdf->addPage();
$pdf->setFooter();
$pdf->writeHTML($html); // $html is the content you want to print
$pdf->Output('example.pdf', 'I'); // I means download the file

Step 2: Save the PDF file

Save the generated PDF file to a temporary location on your server. You can use the file_put_contents function to save the file:

$file_path = 'path/to/temporary/folder/example.pdf';
file_put_contents($file_path, $pdf->Output());

Step 3: Send the email

Use the CodeIgniter Email library to send the email. Here's an example:

$this->load->library('email');

$config = array(
    'protocol' => 'smtp',
    'smtp_host' => 'your_smtp_host',
    'smtp_user' => 'your_smtp_user',
    'smtp_pass' => 'your_smtp_pass',
    'smtp_port' => 587,
    'mailtype' => 'html',
    'charset' => 'utf-8',
);

$this->email->initialize($config);

$this->email->from('your_email_address', 'Your Name');
$this->email->to('recipient_email_address');
$this->email->subject('Example PDF Email');

// Attach the PDF file
$this->email->attach($file_path, 'example.pdf', 'application/pdf');

$this->email->send();

Step 4: Clean up

Make sure to delete the temporary PDF file after sending the email:

unlink($file_path);

Here's the complete code:

<?php

class MyController extends CI_Controller {

    public function send_pdf_email() {
        // Generate the PDF file
        $pdf = new TCPDF();
        $pdf->addPage();
        $pdf->setFooter();
        $pdf->writeHTML($html); // $html is the content you want to print
        $pdf->Output('example.pdf', 'I'); // I means download the file

        // Save the PDF file
        $file_path = 'path/to/temporary/folder/example.pdf';
        file_put_contents($file_path, $pdf->Output());

        // Send the email
        $this->load->library('email');

        $config = array(
            'protocol' => 'smtp',
            'smtp_host' => 'your_smtp_host',
            'smtp_user' => 'your_smtp_user',
            'smtp_pass' => 'your_smtp_pass',
            'smtp_port' => 587,
            'mailtype' => 'html',
            'charset' => 'utf-8',
        );

        $this->email->initialize($config);

        $this->email->from('your_email_address', 'Your Name');
        $this->email->to('recipient_email_address');
        $this->email->subject('Example PDF Email');

        // Attach the PDF file
        $this->email->attach($file_path, 'example.pdf', 'application/pdf');

        $this->email->send();

        // Clean up
        unlink($file_path);
    }

}

Make sure to replace the placeholders (your_smtp_host, your_smtp_user, your_smtp_pass, your_email_address, and recipient_email_address) with your actual email settings.