将通过 Laravel 生成的 PDF 附加到 Mailable

Attaching PDF generated through Laravel to Mailable

目前我使用 laravel-snappy 从页面生成我的 PDF,我这样做主要是因为它与我在一些生成的页面上的一些 JavaScript 脚本配合得非常好。

我知道可以将某种附件附加到可邮寄件上,这就是我一直在听取其他人的建议,直到可通知人员对他们进行更多处理之前使用的方式。

但我不知道是否可以将生成的 PDF 附加到可邮寄的文件中。

目前,我发送生成的 PDF 的路径是:

Route::get('/shipments/download/{shipment}','ShipmentController@downloadPDF');

然后在控制器中发送到此处:

  public function downloadPDF(Shipment $shipment){
            $shipment_details = $shipment->shipment_details;

            $pdf = PDF::loadView('shipments.pdf', compact('shipment','shipment_details'))
                    ->setOption('images', true)
                    ->setOption('enable-javascript', true)
                    ->setOption('javascript-delay', 100);
            return $pdf->download('shipment'.$shipment->url_string.'.pdf');
        }

我的邮件定义如下:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

use App\Shipment;

class newFreightBill extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public $shipment;

    public function __construct(Shipment $shipment)
    {
        $this->shipment = $shipment;
        $this->attachmentURL = $shipment->url_string;
        $this->proNumber = $shipment->pro_number;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from('billing@cmxtrucking.com')
                    ->subject('New Freight Bill Created - '. $this->proNumber)
                    ->view('emails.shipments.created');
    }
}

那么,是否可以附加生成的 PDF 文件?

您可以使用附件通过邮件发送文件。例如:-

public function build()
    {
        return $this->from('billing@cmxtrucking.com')
                    ->subject('New Freight Bill Created - '. $this->proNumber)
                    ->view('emails.shipments.created')
                    ->attach($your_pdf_file_path_goes_here);
    }

这在我尝试时对我有用。希望对你也有用。

我在这里使用 laravel 包 "vsmoraes/laravel-pdf" 生成 pdf

步骤:

1) 使用动态数据渲染视图

2) 将此视图加载到 pdf

3) 附上pdf数据到邮件

$html = view('pdf',compact('result','score'))->render();
$pdf =  PDF::Load($html);

\Mail::send('mail.analysis',['user'=>$data],function($message) use($pdf,$user){
   $message->to($user->email)->subject("Page Speed Aanlysis Generated");
   $message->attachData($pdf->output(),'pdf_name.pdf');
});