Search code examples
laravelemailattachmentemail-attachments

How to make attachment in laravel email


i try to send email in laravel 5.2 and its works. my problem is how to convert a view with its data to PDF then attach it to email i try this

$datastd['fname']=$printqu->std_fname;
$datastd['mname']=$printqu->std_mname;
$datastd['lname']=$printqu->std_lname;
$datastd['email']=$printqu->std_email;
$datastd['email']=$printqu->std_email;
$datastd['orgname']=$printqu->name;
$datastd['depname']=$printqu->Dep_Name;




Mail::send('email.train_form',['datastd'=>$datastd], function($mail) use ($datastd){

    $mail->to($datastd['email'],$datastd['fname'],$datastd['mname'],$datastd['lname'],$datastd['orgname'],$datastd['depname'])->attachData($datastd, 'printPreviewm.pdf')->from('everyone@gmail.com')->subject('Training Forms');

});

the error is time out please i need your help in this


Solution

  • Edit: Sorry, your question is based on Laravel 5.2 and my answer is based on Laravel 5.4. As of generating a PDF can still be done with the DOMPDF package, and the docs for attaching it to a mail can be found in the official Laravel docs here


    Generating a PDF based on a view template can be easily done by using a package such as DOMPDF made by Barryvdh

    Generating a PDF would look something like this

    $view = View::make('any.view', compact('variable'));
    $contents = $view->render();
    $pdf = App::make('dompdf.wrapper');
    $pdf->loadHTML($contents);
    $output = $pdf->output();
    
    Storage::put('/folder/your-file.pdf', $output);
    

    Attaching a document to a mail is pretty simple in Laravel (5.4) [docs]

    // file location
    $file = storage_path('app/folder/your-file.pdf');
    
    // return mail with an attachment
    return $this->view('emails.confirm')
        ->from('me@stackoverflow.com', 'From')->subject('New mail')
        ->with([
            'name' => $this->data['name'],
        ])->attach($file, [
            'as' => 'File name',
            'mime' => 'application/pdf',
        ]);