Search code examples
laravelpdflaravel-5email-attachments

Attaching PDF generated through Laravel to Mailable


At the moment I currently use laravel-snappy to generate my PDFs from pages, I do this primarily because it plays really nice with some JavaScript scripts I have on a few of my generated pages.

I know it's possible to attach an attachment of sorts to a mailable, which is what I have been using at the suggestions of others until the notifiables get a few more things worked on with them.

But I am stuck as to whether or not it's possible to attach a generated PDF to a mailable.

At the moment, I send the PDFs to generate through a route:

Route::get('/shipments/download/{shipment}','ShipmentController@downloadPDF');

Which is then sent to here in the controller:

  public function downloadPDF(Shipment $shipment){
            $shipment_details = $shipment->shipment_details;

            $pdf = PDF::loadView('shipments.pdf', compact('shipment','shipment_details'))
                    ->setOption('images', true)
                    ->setOption('enable-javascript', true)
                    ->setOption('javascript-delay', 100);
            return $pdf->download('shipment'.$shipment->url_string.'.pdf');
        }

My mailable is defined as such:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

use App\Shipment;

class newFreightBill extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public $shipment;

    public function __construct(Shipment $shipment)
    {
        $this->shipment = $shipment;
        $this->attachmentURL = $shipment->url_string;
        $this->proNumber = $shipment->pro_number;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from('billing@cmxtrucking.com')
                    ->subject('New Freight Bill Created - '. $this->proNumber)
                    ->view('emails.shipments.created');
    }
}

So, is it possible to attach a generated PDF?


Solution

  • You can use attach to send files via mail. For example:-

    public function build()
        {
            return $this->from('billing@cmxtrucking.com')
                        ->subject('New Freight Bill Created - '. $this->proNumber)
                        ->view('emails.shipments.created')
                        ->attach($your_pdf_file_path_goes_here);
        }
    

    This worked for me while i was trying. Hope it works for you too.