find($this->invoiceId); if (!$invoice?->customer?->email) { return; } $mail = null; try { $pdf = $pdfService->generate($invoice); $pdfFileName = $pdfService->generateFileName($invoice); $mail = $this->html !== null ? $this->editedMail($templates, $pdf, $pdfFileName) : InvoiceNotificationMail::forInvoice($invoice, $this->type, $this->message, $pdf, $pdfFileName); $this->attachExtras($mail, $invoice, $pdfService); $sent = Mail::to($invoice->customer->email)->send($mail); $this->log($templates, $invoice, $mail, $sent === null ? 'failed' : 'sent'); } catch (Throwable $e) { Log::error('SendInvoiceMailJob failed', [ 'invoice_id' => $invoice->id, 'customer_email' => $invoice->customer->email, 'type' => $this->type, 'error' => $e->getMessage(), ]); if ($mail) { $this->log($templates, $invoice, $mail, 'failed'); } throw $e; } } private function attachExtras(Mailable $mail, Invoice $invoice, InvoicePdfService $pdfService): void { if ($this->attachVat && $invoice->vat_number) { $mail->attachData($pdfService->generate($invoice), $pdfService->vatFileName($invoice), ['mime' => 'application/pdf']); } $contracts = InvoiceAttachment::query() ->where('invoice_id', $invoice->id) ->where('type', InvoiceAttachment::TYPE_CONTRACT) ->whereIn('id', $this->contractIds) ->get(); foreach ($contracts as $contract) { $mail->attachFromStorageDisk($contract->disk, $contract->path, $contract->filename, ['mime' => $contract->mime_type]); } } private function editedMail(EmailTemplateService $templates, string $pdf, string $pdfFileName): GenericTemplateMail { return (new GenericTemplateMail( $this->subject, $this->html, $templates->loadTemplate(InvoiceNotificationMail::SCENARIO)->mailConfig(), InvoiceNotificationMail::SCENARIO, ))->attachData($pdf, $pdfFileName, ['mime' => 'application/pdf']); } private function log(EmailTemplateService $templates, Invoice $invoice, Mailable $mail, string $status): void { $envelope = $mail->envelope(); $addresses = fn (array $list) => implode(', ', array_map(fn ($a) => is_string($a) ? $a : $a->address, $list)); MailLog::create([ 'template_id' => $templates->loadTemplate(InvoiceNotificationMail::SCENARIO)->id, 'subject' => $envelope->subject, 'from_address' => $envelope->from?->address ?? config('mail.from.address'), 'to' => $invoice->customer->email, 'cc' => $addresses($envelope->cc), 'bcc' => $addresses($envelope->bcc), 'customer_id' => $invoice->customer_id, 'order_id' => $invoice->order_id, 'sent_by' => $this->sentBy, 'message' => $mail->render(), 'status' => $status, ]); } }