+sub _email_invoice {
+ my ($self, $data) = @_;
+
+ $data->{config}->load;
+
+ return unless $data->{config}->send_email;
+
+ my @recipients =
+ uniq
+ map { lc }
+ grep { $_ }
+ map { trim($_) }
+ (split(m{,}, $data->{config}->email_recipient_address),
+ $data->{config}->email_recipient_contact ? ($data->{config}->email_recipient_contact->cp_email) : (),
+ $data->{invoice}->{customer}->invoice_mail ? ($data->{invoice}->{customer}->invoice_mail) : ()
+ );
+
+ return unless @recipients;
+
+ my $language = $data->{invoice}->language ? $data->{invoice}->language->template_code : undef;
+ my %create_params = (
+ template => scalar($self->find_template(name => 'invoice', language => $language)),
+ variables => Form->new(''),
+ return => 'file_name',
+ record => $data->{invoice},
+ variable_content_types => {
+ longdescription => 'html',
+ partnotes => 'html',
+ notes => 'html',
+ $::form->get_variable_content_types_for_cvars,
+ },
+ );
+
+ $data->{invoice}->flatten_to_form($create_params{variables}, format_amounts => 1);
+ $create_params{variables}->prepare_for_printing;
+
+ my $pdf_file_name;
+ my $label = $language && Locale::is_supported($language) ? Locale->new($language)->text('Invoice') : $::locale->text('Invoice');
+
+ eval {
+ $pdf_file_name = $self->create_pdf(%create_params);
+
+ $self->_store_pdf_in_webdav ($pdf_file_name, $data->{invoice});
+ $self->_store_pdf_in_filemanagement($pdf_file_name, $data->{invoice});
+
+ for (qw(email_subject email_body)) {
+ _replace_vars(
+ object => $data->{config},
+ invoice => $data->{invoice},
+ vars => $data->{time_period_vars},
+ attribute => $_,
+ attribute_format => ($_ eq 'email_body' ? 'html' : 'text')
+ );
+ }
+
+ my $global_bcc = SL::DB::Default->get->global_bcc;
+ my $overall_error;
+
+ for my $recipient (@recipients) {
+ my $mail = Mailer->new;
+ $mail->{record_id} = $data->{invoice}->id,
+ $mail->{record_type} = 'invoice',
+ $mail->{from} = $data->{config}->email_sender || $::lx_office_conf{periodic_invoices}->{email_from};
+ $mail->{to} = $recipient;
+ $mail->{bcc} = $global_bcc;
+ $mail->{subject} = $data->{config}->email_subject;
+ $mail->{message} = $data->{config}->email_body;
+ $mail->{message} .= SL::DB::Default->get->signature;
+ $mail->{content_type} = 'text/html';
+ $mail->{attachments} = [{
+ path => $pdf_file_name,
+ name => sprintf('%s %s.pdf', $label, $data->{invoice}->invnumber),
+ }];
+
+ my $error = $mail->send;
+
+ if ($error) {
+ push @{ $self->{job_errors} }, $error;
+ push @{ $self->{emailed_failed} }, [ $data->{invoice}, $error ];
+ $overall_error = 1;
+ }
+ }
+
+ push @{ $self->{emailed_invoices} }, $data->{invoice} unless $overall_error;
+
+ 1;
+
+ } or do {
+ push @{ $self->{job_errors} }, $EVAL_ERROR;
+ push @{ $self->{emailed_failed} }, [ $data->{invoice}, $EVAL_ERROR ];
+ };
+
+ unlink $pdf_file_name if $pdf_file_name;
+}
+