Laravel email attaching raw files in memory

44 Views Asked by At
class InvoiceMail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     */
    protected Invoice $invoice;
    public $url, $pdf;

    public function __construct($invoice,$pdf, $url)
    
    {
        //
        $this->invoice = $invoice;
        $this->url = $url;
        $this->pdf = $pdf;
        
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Invoice Mail',
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            markdown:'invoice.email',
            with:[
                'url'=>$this->url,
                'invoice'=> $this->invoice,
            ],
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, \Illuminate\Mail\Mailables\Attachment>
     */
    public function attachments(): array
    {
        //$pdfString = $this->pdf->saveHTML();
        return [
            Attachment::fromData(fn () => $this->pdf, 'invoice.pdf')
                    ->withMime('application/pdf'),
        ];
    }
} 

I am trying to send an email with a PDF attachment but I get the exception : Serialization of 'DOMDocument' is not allowed, unless serialization methods are implemented in a subclass. Am using laravel 10*. I have used the fromData attachment method as described in the documentation but for some reason I can't figure what's not happening or what am doing wrong. Anyone who has come across this and overcome this? Any help would be highly appreciated. I followed:

Raw Data Attachments

The fromData attachment method may be used to attach a raw string of bytes as an attachment. For example, you might use this method if you have generated a PDF in memory and want to attach it to the email without writing it to disk. The fromData method accepts a closure which resolves the raw data bytes as well as the name that the attachment should be assigned:

/**
 * Get the attachments for the message.
 *
 * @return array<int, \Illuminate\Mail\Mailables\Attachment>
 */
public function attachments(): array
{
    return [
        Attachment::fromData(fn () => $this->pdf, 'Report.pdf')
                ->withMime('application/pdf'),
    ];
}

from Laravel documentation.

1

There are 1 best solutions below

0
dz0nika On

With the pretense that the Pdf is setup correctly, you just need to define the output of the pdf in the attachment. Your code should be, sorry I cant seem to find the documentation for this method but I had the same issue as you and this solved it

Attachment::fromData(fn () => $this->pdf->output(), 'Report.pdf')
                ->withMime('application/pdf'),