nicwek's avatar

Send Dymamic Email with Generated PDF

I am trying to creating an e-commerce platform where an auto-generated pdf of clients' orders is sent to their emails as an attachment. I have been through several forums and I see most people are hardcoding the user email address which is not my intention. Kindly assist.

In my OrderController:

$pdf = \PDF::loadview('OrderPDF');
    $try = $pdf->output();

    Mail::to($request->user())->send(new OrderSent($order), function ($message) use ($try) {
        $message->attach($try, 'invoice.pdf', [
            'mime' => 'application/pdf',
        ]);
    });

And in my mail class, this:

/**
 * Create a new message instance.
 *
 * @return void
 */
public function __construct(Order $order)
{
    $this->order = $order;
}

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->markdown('mail.customer.order-sent');
}
0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

do the attach in the mailable class

    $pdf = \PDF::loadview('OrderPDF');

    Mail::to($request->user())->send(new OrderSent($order,  $pdf->output());

accept your pdf into the mailable

public $pdf;

public function __construct(Order $order, $pdf)
{
    $this->order = $order;
    $this->pdf = $pdf;
}

public function build()
{
    return $this->markdown('mail.customer.order-sent')
            ->attachData($this->pdf, 'invoice.pdf', [
                    'mime' => 'application/pdf',
                ]);
}

You need to use the attachData method as your pdf is in memory, not on the filesystem

Please or to participate in this conversation.