Generate PDF from view to send email attaching the PDF file without saving it into disk Laravel 5
Asked Answered
M

3

5

I am working on sending email function. Firstly, I want to generate .pdf file from my view. Then I want to attach the generated .pdf file by email without saving it into disk. I use below in my controller:

$pdf = PDF::loadView('getpdf', $data);
Mail::to($to_email)->send(new Mysendmail($post_title, $full_name))
->attachData($pdf->output(), "newfilename.pdf");

And I get this error: "Call to a member function attachData() on null"

If I use below without attachment, it works well:

$pdf = PDF::loadView('getpdf', $data);
Mail::to($to_email)->send(new Mysendmail($post_title, $full_name));

Please advise.

Mummy answered 15/6, 2017 at 6:42 Comment(0)
B
9

I think you need to attach it to the message, not to the mailer.

$pdf = PDF::loadView('getpdf', $data);
$message = new Mysendmail($post_title, $full_name);
$message->attachData($pdf->output(), "newfilename.pdf");
Mail::to($to_email)->send($message);
Bandy answered 15/6, 2017 at 7:6 Comment(5)
That works great! I have another question- how about I want to do the same thing with file upload (.pdf / .doc)? I mean I don't want to save it into disk but attach it directly.Mummy
I think it is pretty much the same way. attachData($file, 'filename')Bandy
I tried this. attachData($request->file('file')->getClientOriginalExtension(), 'filename') . As the result, it does send attachement but the attached file can't be open- it is corrupted.Mummy
getClientOriginalExtension gives the extension of the file. Try attachData($request->file('file')->getRealPath(), 'filename');Bandy
My working way is $message->attach($request->file('file')->getRealPath(), array('as' => 'filename', 'mime' => $request->file('file')->getMimeType()));Mummy
B
1

Just use 'mime' => 'application/pdf', at last of your code. Simple!

$pdf = PDF::loadView('getpdf', $data); 
Mail::to($to_email)->send(new Mysendmail($post_title, $full_name)) 
->attachData($pdf->output(), "newfilename.pdf"), [ 
'mime' => 'application/pdf', 
]);
Blooded answered 28/8, 2021 at 22:52 Comment(0)
B
0

Just use 'mime' => 'application/pdf', at last of your code. Simple!

` $pdf = PDF::loadView('getpdf', $data); Mail::to($to_email)->send(new Mysendmail($post_title, $full_name)) ->attachData($pdf->output(), "newfilename.pdf"), [ 'mime' => 'application/pdf', ]); `
Blooded answered 28/8, 2021 at 22:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.