Ad

Queuing Mail With AttachData In Laravel 5.1 / OctoberCMS

- 1 answer

The following IS working when I use Mail::send

$email = '[email protected]';
$name = 'My Name';
$invoice = InvoicePdf::generate($invoice_id); // generates PDF as raw data

Mail::send('mail.template', null, function($message) use ($name, $email, $invoice) {

    $message->to($email, $name);
    $message->subject('Thank you for your order!');
    $message->attachData($invoicePdf, 'invoice.pdf', ['mime' => 'application/pdf']);

});

It works fine and an email is generated with the correct PDF attachment.

However, if I change Mail::send to Mail::queue then I receive the following error:

Unable to JSON encode payload. Error code: 5

/var/www/html/october/vendor/laravel/framework/src/Illuminate/Queue/Queue.php line 90

If I take the $message->attachData(); line out then it works even with Mail::queue so it seems like the raw data from the attachment is causing issues with the queue but there's nothing in the relevant October or Laravel docs about how to deal with this.

Ad

Answer

May be its because $invoicePdf data is raw data of PDF file and php can not process that data (attachData) when saving to database.

hmm, alternative you can generate file and then just attach file path to mail and then add to queue.

// generate tempfile name
$temp_file = tempnam(sys_get_temp_dir(), 'inv');

// this pdf is generated by renatio plugin but you can 
// use your data and save it to disk
PDF::loadTemplate('renatio::invoice')
    ->save($temp_file);

Mail::queue('mail.template', null, function($message) use ($name, $email, $temp_file) {
    $message->to($email, $name);
    $message->subject('Thank you for your order!');
    $message->attach($temp_file, ['as' => 'Your_Invoice.pdf', 'mime' => 'application/pdf']);
});

it should work.

@Joseph pointed that in Laravel 5.5 there is mailable which can be used. @Joseph pointed this solution and it seems working so you can also use this solution if your laravel version is >= 5.5https://laracasts.com/discuss/channels/laravel/sending-email-with-a-pdf-attachment

Thanks @Joseph

Ad
source: stackoverflow.com
Ad