+ # Set defaults & headers
+ $self->{charset} = 'UTF-8';
+ $self->{content_type} ||= "text/plain";
+ $self->{headers} ||= [];
+ push @{ $self->{headers} }, (
+ Subject => $self->{subject},
+ 'Message-ID' => '<' . $self->_create_message_id . '>',
+ 'X-Mailer' => "kivitendo " . SL::Version->get_version,
+ );
+ $self->{mail_attachments} = [];
+
+ my $error;
+ my $ok = eval {
+ # Clean up To/Cc/Bcc address fields
+ $self->_cleanup_addresses;
+ $self->_create_address_headers;
+
+ my $email = $self->_create_message;
+
+ 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) = @_;
+
+ # check for custom/overloaded types and ids (form != controller)
+ my $record_type = $self->{record_type} || $::form->{type};
+ my $record_id = $self->{record_id} || $::form->{id};