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 #======================================================================
 
  29 use File::MimeInfo::Magic;
 
  31 use List::UtilsBy qw(bundle_by);
 
  34 use SL::DB::EmailJournal;
 
  35 use SL::DB::EmailJournalAttachment;
 
  45 my %mail_delivery_modules = (
 
  46   sendmail => 'SL::Mailer::Sendmail',
 
  47   smtp     => 'SL::Mailer::SMTP',
 
  51   my ($type, %params) = @_;
 
  52   my $self = { %params };
 
  53   $parser = new MIME::Parser;
 
  54   $parser->output_under("users");
 
  65     myconfig => \%::myconfig,
 
  68   my $module = $mail_delivery_modules{ $::lx_office_conf{mail_delivery}->{method} };
 
  69   eval "require $module" or return undef;
 
  71   return $module->new(%params);
 
  74 sub _cleanup_addresses {
 
  77   foreach my $item (qw(to cc bcc)) {
 
  78     next unless $self->{$item};
 
  80     $self->{$item} =~ s/\</</g;
 
  81     $self->{$item} =~ s/\$<\$/</g;
 
  82     $self->{$item} =~ s/\>/>/g;
 
  83     $self->{$item} =~ s/\$>\$/>/g;
 
  87 sub _create_message_id {
 
  91   my $domain  =  $self->{from};
 
  95   return  "kivitendo-$self->{version}-" . time() . "-${$}-${num_sent}\@$domain";
 
  98 sub _create_address_headers {
 
 101   # $self->{addresses} collects the recipients for use in e.g. the
 
 102   # SMTP 'RCPT TO:' envelope command. $self->{headers} collects the
 
 103   # headers that make up the actual email. 'BCC' should not be
 
 104   # included there for certain transportation methods (SMTP).
 
 106   $self->{addresses} = {};
 
 108   foreach my $item (qw(from to cc bcc)) {
 
 109     $self->{addresses}->{$item} = [];
 
 110     next if !$self->{$item};
 
 112     my @header_addresses;
 
 114     foreach my $addr_obj (Email::Address->parse($self->{$item})) {
 
 115       push @{ $self->{addresses}->{$item} }, $addr_obj->address;
 
 116       next if $self->{driver}->keep_from_header($item);
 
 118       my $phrase = $addr_obj->phrase();
 
 122         $addr_obj->phrase($phrase);
 
 125       push @header_addresses, encode('MIME-Header',$addr_obj->format);
 
 128     push @{ $self->{headers} }, ( ucfirst($item) => join(', ', @header_addresses) ) if @header_addresses;
 
 132 sub _create_attachment_part {
 
 133   my ($self, $attachment) = @_;
 
 136     Disposition  => 'attachment',
 
 137     Encoding     => 'base64',
 
 140   my $attachment_content;
 
 142   my $email_journal = $::instance_conf->get_email_journal;
 
 144   $::lxdebug->message(LXDebug->DEBUG2(), "mail5 att=" . $attachment . " email_journal=" . $email_journal . " id=" . $attachment->{id});
 
 146   if (ref($attachment) eq "HASH") {
 
 147     $attributes{Path}     = $attachment->{path} || $attachment->{filename};
 
 148     $attributes{Filename} = $attachment->{name};
 
 149     $file_id              = $attachment->{id}   || '0';
 
 150     $attributes{Type}     = $attachment->{type} || 'application/pdf';
 
 151     $attachment_content   = eval { read_file($attachment->{path}) } if $email_journal > 1;
 
 155     $attributes{Path}     =  $attachment;
 
 156     $attributes{Filename} =  $attachment;
 
 157     $attributes{Filename} =~ s:.*\Q$self->{fileid}\E:: if $self->{fileid};
 
 158     $attributes{Filename} =~ s:.*/::g;
 
 160     my $application     = ($attachment =~ /(^\w+$)|\.(html|text|txt|sql)$/) ? 'text' : 'application';
 
 161     $attributes{Type}   = File::MimeInfo::Magic::magic($attachment);
 
 162     $attributes{Type} ||= "${application}/$self->{format}" if $self->{format};
 
 163     $attributes{Type} ||= 'application/octet-stream';
 
 164     $attachment_content = eval { read_file($attachment) } if $email_journal > 1;
 
 167   return undef if $email_journal > 1 && !defined $attachment_content;
 
 169   $attachment_content ||= ' ';
 
 170   $attributes{Charset}  = $self->{charset} if $self->{charset};
 
 172   $::lxdebug->message(LXDebug->DEBUG2(), "mail6 mtype=" . $attributes{Type} . " path=" . $attributes{Path} . " filename=" . $attributes{Filename});
 
 175   if ( $attributes{Type} eq 'message/rfc822' ) {
 
 176     my $fh = IO::File->new($attributes{Path}, "r") or return undef;
 
 177     $ent   = $parser->parse($fh);
 
 179     $ent->head->replace('Content-disposition','attachment; filename='.$attributes{Filename});
 
 182     $ent = MIME::Entity->build(%attributes);
 
 185   push @{ $self->{mail_attachments}} , SL::DB::EmailJournalAttachment->new(
 
 186     name      => $attributes{Filename},
 
 187     mime_type => $attributes{Type},
 
 188     content   => ( $email_journal > 1 ? $attachment_content : ' '),
 
 195 sub _create_message {
 
 198   push @{ $self->{headers} }, (Type => "multipart/mixed");
 
 200   my $top = MIME::Entity->build(@{$self->{headers}});
 
 202   if ($self->{message}) {
 
 204       Data     => encode($self->{charset},$self->{message}),
 
 205       Charset  => $self->{charset},
 
 206       Type     => $self->{contenttype},
 
 207       Encoding => 'quoted-printable',
 
 211   $top->add_part($self->_create_attachment_part($_)) for @{ $self->{attachments} || [] };
 
 219   # Create driver for delivery method (sendmail/SMTP)
 
 220   $self->{driver} = eval { $self->_create_driver };
 
 221   if (!$self->{driver}) {
 
 222     $self->_store_in_journal('failed', 'driver could not be created; check your configuration');
 
 223     return "send email : $@";
 
 226   # Set defaults & headers
 
 227   $self->{charset}       =  'UTF-8';
 
 228   $self->{contenttype} ||=  "text/plain";
 
 230     Subject              => encode('MIME-Header',$self->{subject}),
 
 231     'Message-ID'         => '<' . $self->_create_message_id . '>',
 
 232     'X-Mailer'           => "kivitendo $self->{version}",
 
 234   $self->{mail_attachments} = [];
 
 235   $self->{content_by_name}  = $::instance_conf->get_email_journal == 1 && $::instance_conf->get_doc_files;
 
 239     # Clean up To/Cc/Bcc address fields
 
 240     $self->_cleanup_addresses;
 
 241     $self->_create_address_headers;
 
 243     my $email = $self->_create_message;
 
 245     #$::lxdebug->message(0, "message: " . $email->as_string);
 
 248     my $from_obj = (Email::Address->parse($self->{from}))[0];
 
 250     $self->{driver}->start_mail(from => $from_obj->address, to => [ $self->_all_recipients ]);
 
 251     $self->{driver}->print($email->as_string);
 
 252     $self->{driver}->send;
 
 259   $self->{journalentry} = $self->_store_in_journal;
 
 260   $parser->filer->purge;
 
 262   return $ok ? '' : "send email: $error";
 
 265 sub _all_recipients {
 
 267   $self->{addresses} ||= {};
 
 268   return map { @{ $self->{addresses}->{$_} || [] } } qw(to cc bcc);
 
 271 sub _store_in_journal {
 
 272   my ($self, $status, $extended_status) = @_;
 
 274   my $journal_enable = $::instance_conf->get_email_journal;
 
 276   return if $journal_enable == 0;
 
 278   $status          //= $self->{driver}->status if $self->{driver};
 
 279   $status          //= 'failed';
 
 280   $extended_status //= $self->{driver}->extended_status if $self->{driver};
 
 281   $extended_status //= 'unknown error';
 
 283   my $headers = join "\r\n", (bundle_by { join(': ', @_) } 2, @{ $self->{headers} || [] });
 
 285   my $jentry = SL::DB::EmailJournal->new(
 
 286     sender          => SL::DB::Manager::Employee->current,
 
 287     from            => $self->{from}    // '',
 
 288     recipients      => join(', ', $self->_all_recipients),
 
 289     subject         => $self->{subject} // '',
 
 291     body            => $self->{message} // '',
 
 292     sent_on         => DateTime->now_local,
 
 293     attachments     => \@{ $self->{mail_attachments} },
 
 295     extended_status => $extended_status,