1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   9 # This program is free software; you can redistribute it and/or modify
 
  10 # it under the terms of the GNU General Public License as published by
 
  11 # the Free Software Foundation; either version 2 of the License, or
 
  12 # (at your option) any later version.
 
  14 # This program is distributed in the hope that it will be useful,
 
  15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  17 # GNU General Public License for more details.
 
  18 # You should have received a copy of the GNU General Public License
 
  19 # along with this program; if not, write to the Free Software
 
  20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
  22 #======================================================================
 
  27 use Email::MIME::Creator;
 
  29 use File::MimeInfo::Magic;
 
  31 use List::UtilsBy qw(bundle_by);
 
  34 use SL::DB::EmailJournal;
 
  35 use SL::DB::EmailJournalAttachment;
 
  44 my %mail_delivery_modules = (
 
  45   sendmail => 'SL::Mailer::Sendmail',
 
  46   smtp     => 'SL::Mailer::SMTP',
 
  50   sales_quotation         => 'oe',
 
  51   request_quotation       => 'oe',
 
  53   purchase_order          => 'oe',
 
  56   purchase_invoice        => 'ap',
 
  58   purchase_delivery_order => 'delivery_orders',
 
  59   sales_delivery_order    => 'delivery_orders',
 
  63   my ($type, %params) = @_;
 
  64   my $self = { %params };
 
  75     myconfig => \%::myconfig,
 
  78   my $module = $mail_delivery_modules{ $::lx_office_conf{mail_delivery}->{method} };
 
  79   eval "require $module" or return undef;
 
  81   return $module->new(%params);
 
  84 sub _cleanup_addresses {
 
  87   foreach my $item (qw(to cc bcc)) {
 
  88     next unless $self->{$item};
 
  90     $self->{$item} =~ s/\</</g;
 
  91     $self->{$item} =~ s/\$<\$/</g;
 
  92     $self->{$item} =~ s/\>/>/g;
 
  93     $self->{$item} =~ s/\$>\$/>/g;
 
  97 sub _create_message_id {
 
 101   my $domain  =  $self->{from};
 
 105   return  "kivitendo-" . SL::Version->get_version . "-" . time() . "-${$}-${num_sent}\@$domain";
 
 108 sub _create_address_headers {
 
 111   # $self->{addresses} collects the recipients for use in e.g. the
 
 112   # SMTP 'RCPT TO:' envelope command. $self->{headers} collects the
 
 113   # headers that make up the actual email. 'BCC' should not be
 
 114   # included there for certain transportation methods (SMTP).
 
 116   $self->{addresses} = {};
 
 118   foreach my $item (qw(from to cc bcc)) {
 
 119     $self->{addresses}->{$item} = [];
 
 120     next if !$self->{$item};
 
 122     my @header_addresses;
 
 124     foreach my $addr_obj (Email::Address->parse($self->{$item})) {
 
 125       push @{ $self->{addresses}->{$item} }, $addr_obj->address;
 
 126       next if $self->{driver}->keep_from_header($item);
 
 128       my $phrase = $addr_obj->phrase();
 
 132         $addr_obj->phrase($phrase);
 
 135       push @header_addresses, $addr_obj->format;
 
 138     push @{ $self->{headers} }, ( ucfirst($item) => join(', ', @header_addresses) ) if @header_addresses;
 
 142 sub _create_attachment_part {
 
 143   my ($self, $attachment) = @_;
 
 146     disposition  => 'attachment',
 
 147     encoding     => 'base64',
 
 150   my $attachment_content;
 
 152   my $email_journal = $::instance_conf->get_email_journal;
 
 154   $::lxdebug->message(LXDebug->DEBUG2(), "mail5 att=" . $attachment . " email_journal=" . $email_journal . " id=" . $attachment->{id});
 
 156   if (ref($attachment) eq "HASH") {
 
 157     $attributes{filename}     = $attachment->{name};
 
 158     $file_id                  = $attachment->{id}   || '0';
 
 159     $attributes{content_type} = $attachment->{type} || 'application/pdf';
 
 160     $attachment_content       = $attachment->{content};
 
 161     $attachment_content       = eval { read_file($attachment->{path}) } if !$attachment_content;
 
 164     $attributes{filename} =  $attachment;
 
 165     $attributes{filename} =~ s:.*\Q$self->{fileid}\E:: if $self->{fileid};
 
 166     $attributes{filename} =~ s:.*/::g;
 
 168     my $application             = ($attachment =~ /(^\w+$)|\.(html|text|txt|sql)$/) ? 'text' : 'application';
 
 169     $attributes{content_type}   = File::MimeInfo::Magic::magic($attachment);
 
 170     $attributes{content_type} ||= "${application}/$self->{format}" if $self->{format};
 
 171     $attributes{content_type} ||= 'application/octet-stream';
 
 172     $attachment_content         = eval { read_file($attachment) };
 
 175   return undef if $email_journal > 1 && !defined $attachment_content;
 
 177   $attachment_content ||= ' ';
 
 178   $attributes{charset}  = $self->{charset} if $self->{charset} && ($attributes{content_type} =~ m{^text/});
 
 180   $::lxdebug->message(LXDebug->DEBUG2(), "mail6 mtype=" . $attributes{content_type} . " filename=" . $attributes{filename});
 
 183   if ( $attributes{content_type} eq 'message/rfc822' ) {
 
 184     $ent = Email::MIME->new($attachment_content);
 
 186     $ent = Email::MIME->create(
 
 187       attributes => \%attributes,
 
 188       body       => $attachment_content,
 
 192   # Due to a bug in Email::MIME it's not enough to hand over the encoded file name in the "attributes" hash in the
 
 193   # "create" call. Email::MIME iterates over the keys in the hash, and depending on which key it has already seen during
 
 194   # the iteration it might revert the encoding. As Perl's hash key order is randomized for each Perl run, this means
 
 195   # that the file name stays unencoded sometimes.
 
 196   # Setting the header manually after the "create" call circumvents this problem.
 
 197   $ent->header_set('Content-disposition' => 'attachment; filename="' . encode('MIME-Q', $attributes{filename}) . '"');
 
 199   push @{ $self->{mail_attachments}} , SL::DB::EmailJournalAttachment->new(
 
 200     name      => $attributes{filename},
 
 201     mime_type => $attributes{content_type},
 
 202     content   => ( $email_journal > 1 ? $attachment_content : ' '),
 
 209 sub _create_message {
 
 214   push @{ $self->{headers} }, (Type => "multipart/mixed");
 
 216   if ($self->{message}) {
 
 217     push @parts, Email::MIME->create(
 
 219         content_type => $self->{content_type},
 
 220         charset      => $self->{charset},
 
 221         encoding     => 'quoted-printable',
 
 223       body_str => $self->{message},
 
 226     push @{ $self->{headers} }, (
 
 227       'Content-Type' => qq|$self->{content_type}; charset="$self->{charset}"|,
 
 231   push @parts, grep { $_ } map { $self->_create_attachment_part($_) } @{ $self->{attachments} || [] };
 
 233   return Email::MIME->create(
 
 234       header_str => $self->{headers},
 
 242   # Create driver for delivery method (sendmail/SMTP)
 
 243   $self->{driver} = eval { $self->_create_driver };
 
 244   if (!$self->{driver}) {
 
 246     $self->_store_in_journal('failed', 'driver could not be created; check your configuration & log files');
 
 247     $::lxdebug->message(LXDebug::WARN(), "Mailer error during 'send': $error");
 
 252   # Set defaults & headers
 
 253   $self->{charset}        =  'UTF-8';
 
 254   $self->{content_type} ||=  "text/plain";
 
 256     Subject               => $self->{subject},
 
 257     'Message-ID'          => '<' . $self->_create_message_id . '>',
 
 258     'X-Mailer'            => "kivitendo " . SL::Version->get_version,
 
 260   $self->{mail_attachments} = [];
 
 261   $self->{content_by_name}  = $::instance_conf->get_email_journal == 1 && $::instance_conf->get_doc_files;
 
 265     # Clean up To/Cc/Bcc address fields
 
 266     $self->_cleanup_addresses;
 
 267     $self->_create_address_headers;
 
 269     my $email = $self->_create_message;
 
 271     #$::lxdebug->message(0, "message: " . $email->as_string);
 
 274     $::lxdebug->message(LXDebug->DEBUG2(), "mail1 from=".$self->{from}." to=".$self->{to});
 
 275     my $from_obj = (Email::Address->parse($self->{from}))[0];
 
 277     $self->{driver}->start_mail(from => $from_obj->address, to => [ $self->_all_recipients ]);
 
 278     $self->{driver}->print($email->as_string);
 
 279     $self->{driver}->send;
 
 286   # create journal and link to record
 
 287   $self->{journalentry} = $self->_store_in_journal;
 
 288   $self->_create_record_link if $self->{journalentry};
 
 290   return $ok ? '' : ($error || "undefined error");
 
 293 sub _all_recipients {
 
 295   $self->{addresses} ||= {};
 
 296   return map { @{ $self->{addresses}->{$_} || [] } } qw(to cc bcc);
 
 299 sub _store_in_journal {
 
 300   my ($self, $status, $extended_status) = @_;
 
 302   my $journal_enable = $::instance_conf->get_email_journal;
 
 304   return if $journal_enable == 0;
 
 306   $status          //= $self->{driver}->status if $self->{driver};
 
 307   $status          //= 'failed';
 
 308   $extended_status //= $self->{driver}->extended_status if $self->{driver};
 
 309   $extended_status //= 'unknown error';
 
 311   my $headers = join "\r\n", (bundle_by { join(': ', @_) } 2, @{ $self->{headers} || [] });
 
 313   my $jentry = SL::DB::EmailJournal->new(
 
 314     sender          => SL::DB::Manager::Employee->current,
 
 315     from            => $self->{from}    // '',
 
 316     recipients      => join(', ', $self->_all_recipients),
 
 317     subject         => $self->{subject} // '',
 
 319     body            => $self->{message} // '',
 
 320     sent_on         => DateTime->now_local,
 
 321     attachments     => \@{ $self->{mail_attachments} },
 
 323     extended_status => $extended_status,
 
 329 sub _create_record_link {
 
 332   # check for custom/overloaded types and ids (form != controller)
 
 333   my $record_type = $self->{record_type} || $::form->{type};
 
 334   my $record_id   = $self->{record_id}   || $::form->{id};
 
 336   # you may send mails for unsaved objects (no record_id => unlinkable case)
 
 337   if ($self->{journalentry} && $record_id && exists($type_to_table{$record_type})) {
 
 338     RecordLinks->create_links(
 
 340       from_table => $type_to_table{$record_type},
 
 341       from_ids   => $record_id,
 
 342       to_table   => 'email_journal',
 
 343       to_id      => $self->{journalentry},
 
 359 SL::Mailer - Base class for sending mails from kivitendo
 
 363   package SL::BackgroundJob::CreatePeriodicInvoices;
 
 367   my $mail              = Mailer->new;
 
 368   $mail->{from}         = $config{periodic_invoices}->{email_from};
 
 369   $mail->{to}           = $email;
 
 370   $mail->{subject}      = $config{periodic_invoices}->{email_subject};
 
 371   $mail->{content_type} = $filename =~ m/.html$/ ? 'text/html' : 'text/plain';
 
 372   $mail->{message}      = $output;
 
 378 Mail can be send from kivitendo via the sendmail command or the smtp protocol.
 
 381 =head1 INTERNAL DATA TYPES
 
 386 =item C<%mail_delivery_modules>
 
 388   Currently two modules are supported either smtp or sendmail.
 
 390 =item C<%type_to_table>
 
 392   Due to the lack of a single global mapping for $form->{type},
 
 393   type is mapped to the corresponding database table. All types which
 
 394   implement a mail action are currently mapped and should be mapped.
 
 395   Type is either the value of the old form or the newer controller
 
 406 =item C<_create_driver>
 
 408 =item C<_cleanup_addresses>
 
 410 =item C<_create_address_headers>
 
 412 =item C<_create_message_id>
 
 414 =item C<_create_attachment_part>
 
 416 =item C<_create_message>
 
 420   If a mail was send successfully the internal functions _store_in_journal
 
 421   is called if email journaling is enabled. If _store_in_journal was executed
 
 422   successfully and the calling form is already persistent (database id) a
 
 423   record_link will be created.
 
 425 =item C<_all_recipients>
 
 427 =item C<_store_in_journal>
 
 429 =item C<_create_record_link $self->{journalentry}, $::form->{id}, $self->{record_id}>
 
 432   If $self->{journalentry} and either $self->{record_id} or $::form->{id} (checked in
 
 433   this order) exists a record link from record to email journal is created.
 
 434   Will fail silently if record_link creation wasn't successful (same behaviour as