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);
 
  32 use List::Util qw(sum);
 
  35 use SL::DB::EmailJournal;
 
  36 use SL::DB::EmailJournalAttachment;
 
  38 use SL::Locale::String qw(t8);
 
  46 my %mail_delivery_modules = (
 
  47   sendmail => 'SL::Mailer::Sendmail',
 
  48   smtp     => 'SL::Mailer::SMTP',
 
  52   sales_quotation         => 'oe',
 
  53   request_quotation       => 'oe',
 
  55   purchase_order          => 'oe',
 
  58   purchase_invoice        => 'ap',
 
  60   purchase_delivery_order => 'delivery_orders',
 
  61   sales_delivery_order    => 'delivery_orders',
 
  66   my ($type, %params) = @_;
 
  67   my $self = { %params };
 
  78     myconfig => \%::myconfig,
 
  81   my $module = $mail_delivery_modules{ $::lx_office_conf{mail_delivery}->{method} };
 
  82   eval "require $module" or return undef;
 
  84   return $module->new(%params);
 
  87 sub _cleanup_addresses {
 
  90   foreach my $item (qw(to cc bcc)) {
 
  91     next unless $self->{$item};
 
  93     $self->{$item} =~ s/\</</g;
 
  94     $self->{$item} =~ s/\$<\$/</g;
 
  95     $self->{$item} =~ s/\>/>/g;
 
  96     $self->{$item} =~ s/\$>\$/>/g;
 
 100 sub _create_message_id {
 
 104   my $domain  =  $self->{from};
 
 108   return  "kivitendo-" . SL::Version->get_version . "-" . time() . "-${$}-${num_sent}\@$domain";
 
 111 sub _create_address_headers {
 
 114   # $self->{addresses} collects the recipients for use in e.g. the
 
 115   # SMTP 'RCPT TO:' envelope command. $self->{headers} collects the
 
 116   # headers that make up the actual email. 'BCC' should not be
 
 117   # included there for certain transportation methods (SMTP).
 
 119   $self->{addresses} = {};
 
 121   foreach my $item (qw(from to cc bcc)) {
 
 122     $self->{addresses}->{$item} = [];
 
 123     next if !$self->{$item};
 
 125     my @header_addresses;
 
 126     my @addresses = Email::Address->parse($self->{$item});
 
 128     # if either no address was parsed or
 
 129     # there are more than 3 characters per parsed email extra, assume the the user has entered bunk
 
 131        die t8('"#1" seems to be a faulty list of email addresses. No addresses could be extracted.',
 
 134     } elsif ((length($self->{$item}) - sum map { length $_->original } @addresses) / @addresses > 3) {
 
 135        die t8('"#1" seems to be a faulty list of email addresses. After extracing addresses (#2) too many characters are left.',
 
 136          $self->{$item}, join ', ', map { $_->original } @addresses,
 
 140     foreach my $addr_obj (@addresses) {
 
 141       push @{ $self->{addresses}->{$item} }, $addr_obj->address;
 
 142       next if $self->{driver}->keep_from_header($item);
 
 144       my $phrase = $addr_obj->phrase();
 
 148         $addr_obj->phrase($phrase);
 
 151       push @header_addresses, $addr_obj->format;
 
 154     push @{ $self->{headers} }, ( ucfirst($item) => join(', ', @header_addresses) ) if @header_addresses;
 
 158 sub _create_attachment_part {
 
 159   my ($self, $attachment) = @_;
 
 162     disposition  => 'attachment',
 
 163     encoding     => 'base64',
 
 166   my $attachment_content;
 
 168   my $email_journal = $::instance_conf->get_email_journal;
 
 170   if (ref($attachment) eq "HASH") {
 
 171     $attributes{filename}     = $attachment->{name};
 
 172     $file_id                  = $attachment->{id}   || '0';
 
 173     $attributes{content_type} = $attachment->{type} || 'application/pdf';
 
 174     $attachment_content       = $attachment->{content};
 
 175     $attachment_content       = eval { read_file($attachment->{path}) } if !$attachment_content;
 
 178     $attributes{filename} =  $attachment;
 
 179     $attributes{filename} =~ s:.*\Q$self->{fileid}\E:: if $self->{fileid};
 
 180     $attributes{filename} =~ s:.*/::g;
 
 182     my $application             = ($attachment =~ /(^\w+$)|\.(html|text|txt|sql)$/) ? 'text' : 'application';
 
 183     $attributes{content_type}   = File::MimeInfo::Magic::magic($attachment);
 
 184     $attributes{content_type} ||= "${application}/$self->{format}" if $self->{format};
 
 185     $attributes{content_type} ||= 'application/octet-stream';
 
 186     $attachment_content         = eval { read_file($attachment) };
 
 189   return undef if $email_journal > 1 && !defined $attachment_content;
 
 191   $attachment_content ||= ' ';
 
 192   $attributes{charset}  = $self->{charset} if $self->{charset} && ($attributes{content_type} =~ m{^text/});
 
 195   if ( $attributes{content_type} eq 'message/rfc822' ) {
 
 196     $ent = Email::MIME->new($attachment_content);
 
 198     $ent = Email::MIME->create(
 
 199       attributes => \%attributes,
 
 200       body       => $attachment_content,
 
 204   # Due to a bug in Email::MIME it's not enough to hand over the encoded file name in the "attributes" hash in the
 
 205   # "create" call. Email::MIME iterates over the keys in the hash, and depending on which key it has already seen during
 
 206   # the iteration it might revert the encoding. As Perl's hash key order is randomized for each Perl run, this means
 
 207   # that the file name stays unencoded sometimes.
 
 208   # Setting the header manually after the "create" call circumvents this problem.
 
 209   $ent->header_set('Content-disposition' => 'attachment; filename="' . encode('MIME-Q', $attributes{filename}) . '"');
 
 211   push @{ $self->{mail_attachments}} , SL::DB::EmailJournalAttachment->new(
 
 212     name      => $attributes{filename},
 
 213     mime_type => $attributes{content_type},
 
 214     content   => ( $email_journal > 1 ? $attachment_content : ' '),
 
 221 sub _create_message {
 
 226   if ($self->{message}) {
 
 227     push @parts, Email::MIME->create(
 
 229         content_type => $self->{content_type},
 
 230         charset      => $self->{charset},
 
 231         encoding     => 'quoted-printable',
 
 233       body_str => $self->{message},
 
 236     push @{ $self->{headers} }, (
 
 237       'Content-Type' => qq|$self->{content_type}; charset="$self->{charset}"|,
 
 241   push @parts, grep { $_ } map { $self->_create_attachment_part($_) } @{ $self->{attachments} || [] };
 
 243   return Email::MIME->create(
 
 244       header_str => $self->{headers},
 
 252   # Create driver for delivery method (sendmail/SMTP)
 
 253   $self->{driver} = eval { $self->_create_driver };
 
 254   if (!$self->{driver}) {
 
 256     $self->_store_in_journal('failed', 'driver could not be created; check your configuration & log files');
 
 257     $::lxdebug->message(LXDebug::WARN(), "Mailer error during 'send': $error");
 
 262   # Set defaults & headers
 
 263   $self->{charset}        =  'UTF-8';
 
 264   $self->{content_type} ||=  "text/plain";
 
 265   $self->{headers}      ||=  [];
 
 266   push @{ $self->{headers} }, (
 
 267     Subject               => $self->{subject},
 
 268     'Message-ID'          => '<' . $self->_create_message_id . '>',
 
 269     'X-Mailer'            => "kivitendo " . SL::Version->get_version,
 
 271   $self->{mail_attachments} = [];
 
 275     # Clean up To/Cc/Bcc address fields
 
 276     $self->_cleanup_addresses;
 
 277     $self->_create_address_headers;
 
 279     my $email = $self->_create_message;
 
 281     my $from_obj = (Email::Address->parse($self->{from}))[0];
 
 283     $self->{driver}->start_mail(from => $from_obj->address, to => [ $self->_all_recipients ]);
 
 284     $self->{driver}->print($email->as_string);
 
 285     $self->{driver}->send;
 
 292   # create journal and link to record
 
 293   $self->{journalentry} = $self->_store_in_journal;
 
 294   $self->_create_record_link if $self->{journalentry};
 
 296   return $ok ? '' : ($error || "undefined error");
 
 299 sub _all_recipients {
 
 301   $self->{addresses} ||= {};
 
 302   return map { @{ $self->{addresses}->{$_} || [] } } qw(to cc bcc);
 
 305 sub _store_in_journal {
 
 306   my ($self, $status, $extended_status) = @_;
 
 308   my $journal_enable = $::instance_conf->get_email_journal;
 
 310   return if $journal_enable == 0;
 
 312   $status          //= $self->{driver}->status if $self->{driver};
 
 313   $status          //= 'failed';
 
 314   $extended_status //= $self->{driver}->extended_status if $self->{driver};
 
 315   $extended_status //= 'unknown error';
 
 317   my $headers = join "\r\n", (bundle_by { join(': ', @_) } 2, @{ $self->{headers} || [] });
 
 319   my $jentry = SL::DB::EmailJournal->new(
 
 320     sender          => SL::DB::Manager::Employee->current,
 
 321     from            => $self->{from}    // '',
 
 322     recipients      => join(', ', $self->_all_recipients),
 
 323     subject         => $self->{subject} // '',
 
 325     body            => $self->{message} // '',
 
 326     sent_on         => DateTime->now_local,
 
 327     attachments     => \@{ $self->{mail_attachments} },
 
 329     extended_status => $extended_status,
 
 335 sub _create_record_link {
 
 338   # check for custom/overloaded types and ids (form != controller)
 
 339   my $record_type = $self->{record_type} || $::form->{type};
 
 340   my $record_id   = $self->{record_id}   || $::form->{id};
 
 342   # you may send mails for unsaved objects (no record_id => unlinkable case)
 
 343   if ($self->{journalentry} && $record_id && exists($type_to_table{$record_type})) {
 
 344     RecordLinks->create_links(
 
 346       from_table => $type_to_table{$record_type},
 
 347       from_ids   => $record_id,
 
 348       to_table   => 'email_journal',
 
 349       to_id      => $self->{journalentry},
 
 365 SL::Mailer - Base class for sending mails from kivitendo
 
 369   package SL::BackgroundJob::CreatePeriodicInvoices;
 
 373   my $mail              = Mailer->new;
 
 374   $mail->{from}         = $config{periodic_invoices}->{email_from};
 
 375   $mail->{to}           = $email;
 
 376   $mail->{subject}      = $config{periodic_invoices}->{email_subject};
 
 377   $mail->{content_type} = $filename =~ m/.html$/ ? 'text/html' : 'text/plain';
 
 378   $mail->{message}      = $output;
 
 384 Mail can be sent from kivitendo via the sendmail command or the smtp protocol.
 
 387 =head1 INTERNAL DATA TYPES
 
 392 =item C<%mail_delivery_modules>
 
 394   Currently two modules are supported: smtp or sendmail.
 
 396 =item C<%type_to_table>
 
 398   Due to the lack of a single global mapping for $form->{type},
 
 399   type is mapped to the corresponding database table. All types which
 
 400   implement a mail action are currently mapped and should be mapped.
 
 401   Type is either the value of the old form or the newer controller
 
 412 =item C<_create_driver>
 
 414 =item C<_cleanup_addresses>
 
 416 =item C<_create_address_headers>
 
 418 =item C<_create_message_id>
 
 420 =item C<_create_attachment_part>
 
 422 =item C<_create_message>
 
 426   If a mail was sent successfully the internal function _store_in_journal
 
 427   is called if email journaling is enabled. If _store_in_journal was executed
 
 428   successfully and the calling form is already persistent (database id) a
 
 429   record_link will be created.
 
 431 =item C<_all_recipients>
 
 433 =item C<_store_in_journal>
 
 435 =item C<_create_record_link $self->{journalentry}, $::form->{id}, $self->{record_id}>
 
 438   If $self->{journalentry} and either $self->{record_id} or $::form->{id} (checked in
 
 439   this order) exist a record link from record to email journal is created.
 
 440   It is possible to provide an array reference with more than one id in
 
 441   $self->{record_id} or $::form->{id}. In this case all records are linked to
 
 443   Will fail silently if record_link creation wasn't successful (same behaviour as