Laravel 发送附有多个 PDF 的电子邮件

时间:2021-03-02 07:21:40

标签: laravel email-attachments laravel-mail

我正在发送一封附有多个 PDF 的电子邮件。我的发票控制器中有一段代码,它发送附有单个 pdf 的电子邮件。

for ($i = 0; $i < sizeof($email); $i++) { // send to multiple emails
            if ($email[$i] != ";" && $email[$i] != null && $email[$i] != "") {
                $data['email'] = $email[$i];
                try {
                    Mail::send(['html'=>'invoice-attachment'], $data, function($message)use($data,$pdf,$filename) {
                        $message->from($data['from'])
                        ->to($data["email"])
                        ->subject($data["subject"])
                        ->attachData($pdf->output(), "$filename");
                    });
                } catch(JWTException $exception){
                    $this->serverstatuscode = "0";
                    $this->serverstatusdes = $exception->getMessage();
                }
    
                if (Mail::failures()) { // if email fail
                    $error++;
                }
            }
        }

        if($error > 0) {
            return redirect()->back()->with([
                'message'    => "Error sending reminder email to client",
                'alert-type' => 'error',
            ]);
        } else {
            return redirect()->back()->with([
                'message'    => "Reminder emails sent to client successfully",
                'alert-type' => 'success',
            ]);
        }

生成PDF(与Voyager相关)的代码如下:

            if (strlen($dataType->model_name) != 0) { // Model name => App\WhmcsClient
                $model = app($dataType->model_name);
    
                // Use withTrashed() if model uses SoftDeletes and if toggle is selected
                if ($model && in_array(SoftDeletes::class, class_uses($model))) {
                    $model = $model->withTrashed();
                }
                if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope'.ucfirst($dataType->scope))) {
                    $model = $model->{$dataType->scope}();
                }
                $dataTypeContent = call_user_func([$model, 'findOrFail'], $id);
                if ($dataTypeContent->deleted_at) {
                    $isSoftDeleted = true;
                }
            } else {
                // If Model doest exist, get data from table name
                $dataTypeContent = DB::table($dataType->name)->where('id', $id)->first();
            }
    
            // Replace relationships' keys for labels and create READ links if a slug is provided.
            $dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType, true);
    
            // If a column has a relationship associated with it, we do not want to show that field
            $this->removeRelationshipField($dataType, 'read');
    
            // Check permission
            $this->authorize('read', $dataTypeContent);
    
            // Check if BREAD is Translatable
            $isModelTranslatable = is_bread_translatable($dataTypeContent);
    
            $view = 'voyager::bread.read';
    
            if (view()->exists("voyager::$slug.read")) {
                $view = "voyager::$slug.read";
            }
    
            //login user id as sales person who create project
            $userID = Auth::user()->id;
            $roleID = Auth::user()->role_id;
            
            $WhmcsClientModel = new App\WhmcsClientsInvoice();
            $objInvoice = $WhmcsClientModel::find($id);
            
            // check if the invoice has been converted to project
            $Project = new App\Project();
            $blnProjectExists = $Project::where('whmcs_invoice_id', $objInvoice->id)->exists();
    
            // find project id
            $projID = $Project::select('id')->where('whmcs_invoice_id', $id)->first();
    
            // check if the invoice is the owner created or Admin
            if($dataTypeContent->user_id == $userID || $roleID == 1 || $roleID == 2 || Auth::user()->hasRole('PM') || $roleID == 5 || $roleID == 6 || $dataTypeContent->extra_role == "$userID") {
                
                if(isset($dataTypeContent->quotation_id)){
                    $quotation = App\Quotation::find($dataTypeContent->quotation_id);
                    $objQuodetail = $quotation->quodetail->sortBy('position');
                    // get Whmcs Client Detail
                    $ClientDetails = App\WhmcsClient::find($quotation->whmcs_client_id);
                }
                else{
                    $quotation = App\RecurringInvoice::find($dataTypeContent->recurringID);
                    $objQuodetail = App\RecurringInvoiceDetail::where('recurringID',$dataTypeContent->recurringID)->orderBy('position')->get();
                    // get Whmcs Client Detail
                    $ClientDetails = App\WhmcsClient::find($quotation->whmcs_client_id);
                    //$objQuodetail = $quotation->quodetail->sortBy('position');
                }
                
                $name = '';
                $users = App\User::find($dataTypeContent->user_id);
                if(isset($users)){
                $name = $users->name;
                }
                // get invoice history detail
                $InvoiceHistory = App\InvoiceHistory::where('whmcs_clients_invoices_id', '=', $dataTypeContent->id)->get();
                
                $lastInvoiceHistory = App\InvoiceHistory::where('whmcs_clients_invoices_id', '=', $dataTypeContent->id)->latest('created_at')->first();
                
                $UserDetail = '';
                $agent = '';
                if($roleID == 3){
                    $UserDetail = UserDetail::where('user_id','=',$userID)->first();
                    $agent = $UserDetail->agent_type;
                }
                
                $comission = App\Comission::where('quotation_id', '=',$dataTypeContent->quotation_id)->first();
            } else {
                return redirect()
                    ->route("voyager.whmcs-clients-invoices.index")
                    ->with([
                        'message'    => "Sorry, You did not have permission to view the invoice",
                        'alert-type' => 'error',
                    ]);
            }
            
            if(strpos($quotation->notes, '1. The above quotation is valid for 30 days from the date of quotation.') !== false){
                $quotation->notes = str_replace("1. The above quotation is valid for 30 days from the date of quotation.","",$quotation->notes );
                
                $quotation->notes = str_replace("5. Upon signing the quotation you agree to indemnify and keep us against all suits, legal proceedings, claims, damages and losses whatsoever.","",$quotation->notes );
                
                $quotation->notes = str_replace("2.","1.",$quotation->notes);
                $quotation->notes = str_replace("3.","2.",$quotation->notes);
                $quotation->notes = str_replace("4.","3.",$quotation->notes);
            }
                
            $data["quotation"] = $quotation;
            $data["dataType"] = $dataType;
            $data["dataTypeContent"] = $dataTypeContent;
            $data["objQuodetail"] = $objQuodetail;
            $data["ClientDetails"] = $ClientDetails;
            $data["name"] = $name;
            $data["name"] = $users;
            $data["InvoiceHistory"] = $InvoiceHistory;
                
            if($dataTypeContent->invoice_num != null){
                $filename = "Invoice_" .  $dataTypeContent->invoice_num . "_" . $dataTypeContent->invoice_date . ".pdf";
            }
            else{
                $filename = "Invoice_" .  $dataTypeContent->invoice_id . "_" . $dataTypeContent->invoice_date . ".pdf";
            }
                
            //$filename = "Invoice_" .  $dataTypeContent->invoice_id . "_" . $dataTypeContent->invoice_date . ".pdf";
            $pdf = app('dompdf.wrapper')->loadView('invoice-pdf', compact('dataType', 'dataTypeContent', 'quotation', 'objQuodetail', 'ClientDetails','name','InvoiceHistory','users'));

如您所见,我只能发送附有单个 PDF 的电子邮件。如何通过修改我的代码来发送附有多个 PDF 的电子邮件?

0 个答案:

没有答案