Dateimanagement: Alle Anhänge per E-Mail versendbar machen
[kivitendo-erp.git] / SL / Mailer.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 #
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.
13 #
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,
21 # MA 02110-1335, USA.
22 #======================================================================
23
24 package Mailer;
25
26 use Email::Address;
27 use MIME::Entity;
28 use MIME::Parser;
29 use File::MimeInfo::Magic;
30 use File::Slurp;
31 use List::UtilsBy qw(bundle_by);
32
33 use SL::Common;
34 use SL::DB::EmailJournal;
35 use SL::DB::EmailJournalAttachment;
36 use SL::DB::Employee;
37 use SL::Template;
38
39 use strict;
40 use Encode;
41
42 my $num_sent = 0;
43 my $parser;
44
45 my %mail_delivery_modules = (
46   sendmail => 'SL::Mailer::Sendmail',
47   smtp     => 'SL::Mailer::SMTP',
48 );
49
50 sub new {
51   my ($type, %params) = @_;
52   my $self = { %params };
53   $parser = new MIME::Parser;
54   $parser->output_under("users");
55
56   bless $self, $type;
57 }
58
59 sub _create_driver {
60   my ($self) = @_;
61
62   my %params = (
63     mailer   => $self,
64     form     => $::form,
65     myconfig => \%::myconfig,
66   );
67
68   my $module = $mail_delivery_modules{ $::lx_office_conf{mail_delivery}->{method} };
69   eval "require $module" or return undef;
70
71   return $module->new(%params);
72 }
73
74 sub _cleanup_addresses {
75   my ($self) = @_;
76
77   foreach my $item (qw(to cc bcc)) {
78     next unless $self->{$item};
79
80     $self->{$item} =~ s/\&lt;/</g;
81     $self->{$item} =~ s/\$<\$/</g;
82     $self->{$item} =~ s/\&gt;/>/g;
83     $self->{$item} =~ s/\$>\$/>/g;
84   }
85 }
86
87 sub _create_message_id {
88   my ($self) = @_;
89
90   $num_sent  +=  1;
91   my $domain  =  $self->{from};
92   $domain     =~ s/.*\@//;
93   $domain     =~ s/>.*//;
94
95   return  "kivitendo-$self->{version}-" . time() . "-${$}-${num_sent}\@$domain";
96 }
97
98 sub _create_address_headers {
99   my ($self) = @_;
100
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).
105
106   $self->{addresses} = {};
107
108   foreach my $item (qw(from to cc bcc)) {
109     $self->{addresses}->{$item} = [];
110     next if !$self->{$item};
111
112     my @header_addresses;
113
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);
117
118       my $phrase = $addr_obj->phrase();
119       if ($phrase) {
120         $phrase =~ s/^\"//;
121         $phrase =~ s/\"$//;
122         $addr_obj->phrase($phrase);
123       }
124
125       push @header_addresses, encode('MIME-Header',$addr_obj->format);
126     }
127
128     push @{ $self->{headers} }, ( ucfirst($item) => join(', ', @header_addresses) ) if @header_addresses;
129   }
130 }
131
132 sub _create_attachment_part {
133   my ($self, $attachment) = @_;
134
135   my %attributes = (
136     Disposition  => 'attachment',
137     Encoding     => 'base64',
138   );
139
140   my $file_id = 0;
141   my $attachment_content;
142   my $email_journal = $::instance_conf->get_email_journal;
143
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;
151
152   } else {
153     # strip path
154     $attributes{Path}     =  $attachment;
155     $attributes{Filename} =  $attachment;
156     $attributes{Filename} =~ s:.*\Q$self->{fileid}\E:: if $self->{fileid};
157     $attributes{Filename} =~ s:.*/::g;
158
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;
164   }
165
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});
170
171 # $attributes{Charset}  = $self->{charset} if lc $application eq 'text' && $self->{charset};
172   $attributes{Charset}  = $self->{charset} if $self->{charset};
173
174   my $ent;
175   if ( $attributes{Type} eq 'message/rfc822' ) {
176     my $fh = IO::File->new($attributes{Path}, "r");
177     if (! defined $fh) {
178       return undef;
179     }
180     $ent = $parser->parse($fh);
181     undef $fh;
182     my $head = $ent->head;
183     $head->replace('Content-disposition','attachment; filename='.$attributes{Filename});
184   } else {
185     $ent = MIME::Entity->build(%attributes);
186   }
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 : ' '),
191     file_id   => $file_id,
192   );
193   return $ent;
194 }
195
196 sub _create_message {
197   my ($self) = @_;
198
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');
206   }
207
208   map { $top->add_part($self->_create_attachment_part($_)) } @{ $self->{attachments} || [] };
209   return $top;
210 }
211
212 sub send {
213   my ($self) = @_;
214
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 : $@";
220   }
221
222   # Set defaults & headers
223   $self->{charset}       =  'UTF-8';
224   $self->{contenttype} ||=  "text/plain";
225   $self->{headers}       =  [
226     Subject              => encode('MIME-Header',$self->{subject}),
227     'Message-ID'         => '<' . $self->_create_message_id . '>',
228     'X-Mailer'           => "kivitendo $self->{version}",
229   ];
230   $self->{mail_attachments} = [];
231   $self->{content_by_name}  = $::instance_conf->get_email_journal == 1 && $::instance_conf->get_doc_files;
232
233   my $error;
234   my $ok = eval {
235     # Clean up To/Cc/Bcc address fields
236     $self->_cleanup_addresses;
237     $self->_create_address_headers;
238
239     my $email = $self->_create_message;
240
241     #$::lxdebug->message(0, "message: " . $email->as_string);
242     # return "boom";
243
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;
247
248     1;
249   };
250
251   $error = $@ if !$ok;
252
253   $self->{journalentry} = $self->_store_in_journal;
254   $parser->filer->purge;
255
256   return $ok ? '' : "send email: $error";
257 }
258
259 sub _all_recipients {
260   my ($self) = @_;
261   $self->{addresses} ||= {};
262   return map { @{ $self->{addresses}->{$_} || [] } } qw(to cc bcc);
263 }
264
265 sub _store_in_journal {
266   my ($self, $status, $extended_status) = @_;
267
268   my $journal_enable = $::instance_conf->get_email_journal;
269
270   return if $journal_enable == 0;
271
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';
276
277   my $headers = join "\r\n", (bundle_by { join(': ', @_) } 2, @{ $self->{headers} || [] });
278
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} // '',
284     headers         => $headers,
285     body            => $self->{message} // '',
286     sent_on         => DateTime->now_local,
287     attachments     => \@{ $self->{mail_attachments} },
288     status          => $status,
289     extended_status => $extended_status,
290   )->save;
291   return $jentry->id;
292 }
293
294 1;