I am trying to send an email with Laravel and attach a generated PDF to the email. The email is sending but the pdf isn't being sent.
Notes: Using Larvel Version 5.5 PHP version >=7.0.0 Library I'm using to generate pdf: https://github.com/niklasravnsborg/laravel-pdf
Here is the code:
<?php
namespace Portal\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use niklasravnsborg\LaravelPdf\Facades\Pdf as PDF;
class PreApprovalEmail extends Mailable
{
use Queueable, SerializesModels;
public $name;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($name)
{
$this->name = $name;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
$this->subject('Pre approval letter');
return $this->view('emails.emailTemplate')->attachData($this->createPDF(), 'generated.pdf', [
'mime' => 'application/pdf',
]);
}
public function createPDF()
{
$data = array(
// data
);
$pdf = PDF::loadView('emails.generatablePDF', $data);
return $pdf->stream('document.pdf');
}
}
Here is the route in my routes/web.php file:
Route::get('/samplemail', function () {
Mail::to("<my_email>@protonmail.com")->send(new PreApprovalEmail("test"));
return view('emails.generatablePDF')
});
According to the docs ( https://laravel.com/docs/5.5/mail ) I should be getting the proper email, including the attachment. I am getting the email, but not the attachment. How can I solve this?
Can you try output
method for your pdf instead of streaming it, as stream first calls the output then builds a new http response:
/**
* @return mixed
*/
public function build()
{
$this->subject('Pre approval letter');
return $this->view('emails.emailTemplate')
->attachData($this->createPDF(), 'generated.pdf');
}
/**
* @return mixed
*/
public function createPDF()
{
$data = [
// data
];
$pdf = PDF::loadView('emails.generatablePDF', $data);
return $pdf->output();
}
Also make sure that your pdf output is correct so do a dd
before attaching it to the email.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.