Laravel Send Email With PDF Attachment

In Laravel, you can send emails with PDF attachments using the built-in email sending functionality and the “dompdf” package for generating PDFs.

  1. Install the “dompdf/dompdf” package by running the command: composer require dompdf/dompdf
  2. In your controller, use the package to generate the PDF. For example:
use Dompdf\Dompdf;

class MyController extends Controller {
    public function sendEmailWithPDF() {
        $pdf = new Dompdf();
        $pdf->loadHtml('<h1>Hello World</h1>');
        $pdf->render();
        $pdf->stream("sample.pdf", array("Attachment" => false));
    }
}

3. In your controller, use Laravel’s built-in email sending functionality to send the email with the PDF attachment. For example:

use Mail;

class MyController extends Controller {
    public function sendEmailWithPDF() {
        $pdf = new Dompdf();
        $pdf->loadHtml('<h1>Hello World</h1>');
        $pdf->render();
        $pdf = $pdf->output();

        $attachment = chunk_split(base64_encode($pdf));

        Mail::send('emails.send', ['title' => 'Email With PDF Attachment'], function($message) use($attachment) {
            $message->to('[email protected]', 'Recipient');
            $message->subject('Email With PDF Attachment');
            $message->attachData($pdf, "sample.pdf");
            $message->from('[email protected]','Sender');
        });
    }
}

Please ensure your email configurations are set correctly in .env and config/mail.php.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *