+ # Set defaults & headers
+ $self->{charset} = 'UTF-8';
+ $self->{content_type} ||= "text/plain";
+ $self->{headers} = [
+ Subject => $self->{subject},
+ 'Message-ID' => '<' . $self->_create_message_id . '>',
+ 'X-Mailer' => "kivitendo " . SL::Version->get_version,
+ ];
+ $self->{mail_attachments} = [];
+ $self->{content_by_name} = $::instance_conf->get_email_journal == 1 && $::instance_conf->get_doc_files;
+
+ my $error;
+ my $ok = eval {
+ # Clean up To/Cc/Bcc address fields
+ $self->_cleanup_addresses;
+ $self->_create_address_headers;
+
+ my $email = $self->_create_message;
+
+ #$::lxdebug->message(0, "message: " . $email->as_string);
+ # return "boom";
+
+ $::lxdebug->message(LXDebug->DEBUG2(), "mail1 from=".$self->{from}." to=".$self->{to});
+ my $from_obj = (Email::Address->parse($self->{from}))[0];
+
+ $self->{driver}->start_mail(from => $from_obj->address, to => [ $self->_all_recipients ]);
+ $self->{driver}->print($email->as_string);
+ $self->{driver}->send;
+
+ 1;
+ };
+
+ $error = $@ if !$ok;
+
+ # create journal and link to record
+ $self->{journalentry} = $self->_store_in_journal;
+ $self->_create_record_link if $self->{journalentry};
+
+ return $ok ? '' : ($error || "undefined error");
+}
+
+sub _all_recipients {
+ my ($self) = @_;
+ $self->{addresses} ||= {};
+ return map { @{ $self->{addresses}->{$_} || [] } } qw(to cc bcc);
+}
+
+sub _store_in_journal {
+ my ($self, $status, $extended_status) = @_;
+
+ my $journal_enable = $::instance_conf->get_email_journal;
+
+ return if $journal_enable == 0;
+
+ $status //= $self->{driver}->status if $self->{driver};
+ $status //= 'failed';
+ $extended_status //= $self->{driver}->extended_status if $self->{driver};
+ $extended_status //= 'unknown error';
+
+ my $headers = join "\r\n", (bundle_by { join(': ', @_) } 2, @{ $self->{headers} || [] });
+
+ my $jentry = SL::DB::EmailJournal->new(
+ sender => SL::DB::Manager::Employee->current,
+ from => $self->{from} // '',
+ recipients => join(', ', $self->_all_recipients),
+ subject => $self->{subject} // '',
+ headers => $headers,
+ body => $self->{message} // '',
+ sent_on => DateTime->now_local,
+ attachments => \@{ $self->{mail_attachments} },
+ status => $status,
+ extended_status => $extended_status,
+ )->save;
+ return $jentry->id;
+}
+
+
+sub _create_record_link {
+ my ($self) = @_;