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',
 
 141   my $attachment_content;
 
 142   my $email_journal = $::instance_conf->get_email_journal;
 
 144   $main::lxdebug->message(LXDebug->DEBUG2(), "mail5 att=".$attachment." email_journal=". $email_journal." id=".$attachment->{id});
 
 145   if (ref($attachment) eq "HASH") {
 
 146     $attributes{Path}     = $attachment->{path} || $attachment->{filename};
 
 147     $attributes{Filename} = $attachment->{name};
 
 148     $file_id              = $attachment->{id}   || '0';
 
 149     $attributes{Type}     = $attachment->{type} || 'application/pdf';
 
 150     $attachment_content   = eval { read_file($attachment->{path}) } if $email_journal > 1;
 
 154     $attributes{Path}     =  $attachment;
 
 155     $attributes{Filename} =  $attachment;
 
 156     $attributes{Filename} =~ s:.*\Q$self->{fileid}\E:: if $self->{fileid};
 
 157     $attributes{Filename} =~ s:.*/::g;
 
 159     my $application     = ($attachment =~ /(^\w+$)|\.(html|text|txt|sql)$/) ? 'text' : 'application';
 
 160     $attributes{Type}   = File::MimeInfo::Magic::magic($attachment);
 
 161     $attributes{Type} ||= "${application}/$self->{format}" if $self->{format};
 
 162     $attributes{Type} ||= 'application/octet-stream';
 
 163     $attachment_content = eval { read_file($attachment) } if $email_journal > 1;
 
 166   return undef if $email_journal > 1 && !defined $attachment_content;
 
 167   $attachment_content ||= ' ';
 
 168   $main::lxdebug->message(LXDebug->DEBUG2(), "mail6 mtype=".$attributes{Type}." path=".
 
 169                             $attributes{Path}." filename=".$attributes{Filename});
 
 171 # $attributes{Charset}  = $self->{charset} if lc $application eq 'text' && $self->{charset};
 
 172   $attributes{Charset}  = $self->{charset} if $self->{charset};
 
 175   if ( $attributes{Type} eq 'message/rfc822' ) {
 
 176     my $fh = IO::File->new($attributes{Path}, "r");
 
 180     $ent = $parser->parse($fh);
 
 182     my $head = $ent->head;
 
 183     $head->replace('Content-disposition','attachment; filename='.$attributes{Filename});
 
 185     $ent = MIME::Entity->build(%attributes);
 
 187   push @{ $self->{mail_attachments}} , SL::DB::EmailJournalAttachment->new(
 
 188     name      => $attributes{Filename},
 
 189     mime_type => $attributes{Type},
 
 190     content   => ( $email_journal > 1 ? $attachment_content : ' '),
 
 196 sub _create_message {
 
 199   push @{ $self->{headers} }, ('Type'    =>"multipart/mixed" );
 
 200   my  $top = MIME::Entity->build(@{$self->{headers}});
 
 201   if ($self->{message}) {
 
 202     $top->attach(Data => encode($self->{charset},$self->{message}),
 
 203                  Charset => $self->{charset},
 
 204                  Type => $self->{contenttype},
 
 205                  Encoding    => 'quoted-printable');
 
 208   map { $top->add_part($self->_create_attachment_part($_)) } @{ $self->{attachments} || [] };
 
 215   # Create driver for delivery method (sendmail/SMTP)
 
 216   $self->{driver} = eval { $self->_create_driver };
 
 217   if (!$self->{driver}) {
 
 218     $self->_store_in_journal('failed', 'driver could not be created; check your configuration');
 
 219     return "send email : $@";
 
 222   # Set defaults & headers
 
 223   $self->{charset}       =  'UTF-8';
 
 224   $self->{contenttype} ||=  "text/plain";
 
 226     Subject              => encode('MIME-Header',$self->{subject}),
 
 227     'Message-ID'         => '<' . $self->_create_message_id . '>',
 
 228     'X-Mailer'           => "kivitendo $self->{version}",
 
 230   $self->{mail_attachments} = [];
 
 231   $self->{content_by_name}  = $::instance_conf->get_email_journal == 1 && $::instance_conf->get_doc_files;
 
 235     # Clean up To/Cc/Bcc address fields
 
 236     $self->_cleanup_addresses;
 
 237     $self->_create_address_headers;
 
 239     my $email = $self->_create_message;
 
 241     #$::lxdebug->message(0, "message: " . $email->as_string);
 
 244     $self->{driver}->start_mail(from => encode('MIME-Header',$self->{from}), to => [ $self->_all_recipients ]);
 
 245     $self->{driver}->print($email->as_string);
 
 246     $self->{driver}->send;
 
 253   $self->{journalentry} = $self->_store_in_journal;
 
 254   $parser->filer->purge;
 
 256   return $ok ? '' : "send email: $error";
 
 259 sub _all_recipients {
 
 261   $self->{addresses} ||= {};
 
 262   return map { @{ $self->{addresses}->{$_} || [] } } qw(to cc bcc);
 
 265 sub _store_in_journal {
 
 266   my ($self, $status, $extended_status) = @_;
 
 268   my $journal_enable = $::instance_conf->get_email_journal;
 
 270   return if $journal_enable == 0;
 
 272   $status          //= $self->{driver}->status if $self->{driver};
 
 273   $status          //= 'failed';
 
 274   $extended_status //= $self->{driver}->extended_status if $self->{driver};
 
 275   $extended_status //= 'unknown error';
 
 277   my $headers = join "\r\n", (bundle_by { join(': ', @_) } 2, @{ $self->{headers} || [] });
 
 279   my $jentry = SL::DB::EmailJournal->new(
 
 280     sender          => SL::DB::Manager::Employee->current,
 
 281     from            => $self->{from}    // '',
 
 282     recipients      => join(', ', $self->_all_recipients),
 
 283     subject         => $self->{subject} // '',
 
 285     body            => $self->{message} // '',
 
 286     sent_on         => DateTime->now_local,
 
 287     attachments     => \@{ $self->{mail_attachments} },
 
 289     extended_status => $extended_status,