Alex
Alex

Reputation: 2775

Laravel: grab html from the view and send it as a mail attachment

I have a blade template that generates the content that I need:

invoice.blade.php

//nothing interesting here, just html

I have a route to access this view by a link:

web.php

Route::get('/invoice/{id}', function ($id) {return view('invoice.invoice')->with('id', $id);});

What is the better way to send the html file (which is generated by this route) by laravel mailer? I tried to do it in this way:

$file = file_get_contents(url('invoice/1'));    
Mail::send([], [], function ($message) use ($file) {
       ...
       $message->attach($file, [
          'as' => 'file-name',
          'mime' => 'text/html',
       ]);
    });

Mailer works fine, but get an error about maximum execution time exceeded for file_get_contents (I know it can be fixed by allow_url_fopen PHP setting), also I know about curl method, but it also not available for test for me right now by server settings. So my question is: do we have another way to implement this? Which way is better (faster)?

Upvotes: 1

Views: 1458

Answers (1)

Alex
Alex

Reputation: 2775

Solved by view()->render() and mailer ->attachData() functions.

$file = view('invoice.invoice_inline', ['id' => $id])->render();
Mail::send([], [], function ($message) use ($file) {
   ...
   $message->attachData($file, 'filename.html', ['mime' => 'text/html']);
});

Upvotes: 4

Related Questions