codeigniter send pdf file as email attachment

17,083

Solution 1

Took my a while to find the answer, hope it helps anyone in the future:

    // Get email address and base64 via ajax
    $email = $this->input->post('email');
    $base64 = $this->input->post('base64');

    $base64 = str_replace('data:application/pdf;base64,', '', $base64);
    $base64 = str_replace(' ', '+', $base64);

    $data = base64_decode($base64);

    // Locally emails do now work, so I use this to connect through my gmail account to send emails
    $config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'ssl://smtp.googlemail.com',
        'smtp_port' => 465,
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'MyEmailPassword',
        'mailtype'  => 'html', 
        'charset'   => 'iso-8859-1'
    );

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

    $this->email->set_newline("\r\n");
    $this->email->to($email);
    $this->email->from('[email protected]', 'base64');
    $this->email->subject('base64');
    // Using the string_attach($str_file, $filename, $mime, $disposition = 'attachment')
    // function located in CodeIgniter\application\libraries\Email.php
    $this->email->string_attach($data, 'base64.pdf', 'application/pdf');

    $this->email->send();

Solution 2

 /*its batter to make function*/ 

 /*-------COPY THIS CODE---- */

  $newFile  = 'Path/to/save/filename.pdf';
  $obj = new $this->pdf;
  $obj->SetSubject('BLAH BLAH'); // set document information
  $obj->SetKeywords('Blah, Blah, Blah'); 
  $obj->AddPage(); // add a page
  $obj->SetFont('helvetica', '', 6);
  $obj->writeHTML("Your text goes here", true, false, false, false, '');
  $obj->Output($newFile, 'F'); //Close and output PDF document

 /*-------SENDING EMAIL---- */

 $this->load->library('email');
 $this->email->from('[email protected]', 'Example');
 $this->email->to('[email protected]');
 $this->email->subject('Subject Goes Here');
 $this->email->message('Message goes here');
 $this->email->attach($newFile);
 $this->email->send();
Share:
17,083
Ramesh Paul
Author by

Ramesh Paul

Senior software engineer at Threshold Software Solutions.

Updated on June 04, 2022

Comments

  • Ramesh Paul
    Ramesh Paul almost 2 years

    I am generating pdf files on fly using TCPDF. By using TCPDF i am getting raw file with base64 encoded now i want to send this raw data as email attachment using codeigniter email helper function.

    How can do this?