Muhammad Rohail
Muhammad Rohail

Reputation: 291

Laravel: attach multiple PDFs to email

Following is a code to send a PDF with email:

        $pdf = PDF::loadHTML($str_html)->setPaper('a4', 'portrait');  

        Mail::send('emails.mail', $data, function($message) use ($data,$pdf){
            $message->from('noreply@...');
            $message->to('...');
            $message->subject('test test');
            //Attach PDF doc
            $message->attachData($pdf->output(),'invoice.pdf');
        });

But my requirement is to send multiple PDFs with email, how can I do this?

Upvotes: 1

Views: 808

Answers (2)

Muhammad Rohail
Muhammad Rohail

Reputation: 291

taibur rahman provides an answer in comment, new PDFs variables must be added in "use", then code will be correct.

Complete Code:

        $pdf = PDF::loadHTML($str_html)->setPaper('a4', 'portrait');

        $pdf2 = PDF::loadHTML($str_html2)->setPaper('a4', 'portrait'); 

        Mail::send('emails.mail', $data, function($message) use ($data, $pdf, $pdf2){
            $message->from('...@...');
            $message->to(...@...);
            $message->subject('test test');
            $message->attachData($pdf->output(),'test.pdf');
            $message->attachData($pdf2->output(),'test2.pdf');

        }); 

Upvotes: 0

taiabur rahman
taiabur rahman

Reputation: 51

$attachments = [
    // first attachment
    '/path/to/file1',

    // second attachment
    '/path/to/file2',
    ...
];

    $pdf = PDF::loadHTML($str_html)->setPaper('a4', 'portrait');  

    Mail::send('emails.mail', $data, function($message) use ($data,$pdf){
        $message->from('noreply@...');
        $message->to('...');
        $message->subject('test test');
        //Attach PDF doc

        foreach($attachments as $filePath){
              $message->attach($filePath);
        }
    });

Upvotes: 2

Related Questions