epic-s6ts
[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 Email::MIME::Creator;
28 use Encode;
29 use File::MimeInfo::Magic;
30 use File::Slurp;
31 use List::UtilsBy qw(bundle_by);
32 use List::Util qw(sum);
33
34 use SL::Common;
35 use SL::DB::EmailJournal;
36 use SL::DB::EmailJournalAttachment;
37 use SL::DB::Employee;
38 use SL::Locale::String qw(t8);
39 use SL::Template;
40 use SL::Version;
41
42 use strict;
43
44 my $num_sent = 0;
45
46 my %mail_delivery_modules = (
47   sendmail => 'SL::Mailer::Sendmail',
48   smtp     => 'SL::Mailer::SMTP',
49 );
50
51 my %type_to_table = (
52   sales_quotation         => 'oe',
53   request_quotation       => 'oe',
54   sales_order             => 'oe',
55   purchase_order          => 'oe',
56   invoice                 => 'ar',
57   credit_note             => 'ar',
58   purchase_invoice        => 'ap',
59   letter                  => 'letter',
60   purchase_delivery_order => 'delivery_orders',
61   sales_delivery_order    => 'delivery_orders',
62   dunning                 => 'dunning',
63 );
64
65 sub new {
66   my ($type, %params) = @_;
67   my $self = { %params };
68
69   bless $self, $type;
70 }
71
72 sub _create_driver {
73   my ($self) = @_;
74
75   my %params = (
76     mailer   => $self,
77     form     => $::form,
78     myconfig => \%::myconfig,
79   );
80
81   my $module = $mail_delivery_modules{ $::lx_office_conf{mail_delivery}->{method} };
82   eval "require $module" or return undef;
83
84   return $module->new(%params);
85 }
86
87 sub _cleanup_addresses {
88   my ($self) = @_;
89
90   foreach my $item (qw(to cc bcc)) {
91     next unless $self->{$item};
92
93     $self->{$item} =~ s/\&lt;/</g;
94     $self->{$item} =~ s/\$<\$/</g;
95     $self->{$item} =~ s/\&gt;/>/g;
96     $self->{$item} =~ s/\$>\$/>/g;
97   }
98 }
99
100 sub _create_message_id {
101   my ($self) = @_;
102
103   $num_sent  +=  1;
104   my $domain  =  $self->{from};
105   $domain     =~ s/.*\@//;
106   $domain     =~ s/>.*//;
107
108   return  "kivitendo-" . SL::Version->get_version . "-" . time() . "-${$}-${num_sent}\@$domain";
109 }
110
111 sub _create_address_headers {
112   my ($self) = @_;
113
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).
118
119   $self->{addresses} = {};
120
121   foreach my $item (qw(from to cc bcc)) {
122     $self->{addresses}->{$item} = [];
123     next if !$self->{$item};
124
125     my @header_addresses;
126     my @addresses = Email::Address->parse($self->{$item});
127
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
130     if (!@addresses) {
131        die t8('"#1" seems to be a faulty list of email addresses. No addresses could be extracted.',
132          $self->{$item},
133        );
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,
137        );
138     }
139
140     foreach my $addr_obj (@addresses) {
141       push @{ $self->{addresses}->{$item} }, $addr_obj->address;
142       next if $self->{driver}->keep_from_header($item);
143
144       my $phrase = $addr_obj->phrase();
145       if ($phrase) {
146         $phrase =~ s/^\"//;
147         $phrase =~ s/\"$//;
148         $addr_obj->phrase($phrase);
149       }
150
151       push @header_addresses, $addr_obj->format;
152     }
153
154     push @{ $self->{headers} }, ( ucfirst($item) => join(', ', @header_addresses) ) if @header_addresses;
155   }
156 }
157
158 sub _create_attachment_part {
159   my ($self, $attachment) = @_;
160
161   my %attributes = (
162     disposition  => 'attachment',
163     encoding     => 'base64',
164   );
165
166   my $attachment_content;
167   my $file_id       = 0;
168   my $email_journal = $::instance_conf->get_email_journal;
169
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;
176
177   } else {
178     $attributes{filename} =  $attachment;
179     $attributes{filename} =~ s:.*\Q$self->{fileid}\E:: if $self->{fileid};
180     $attributes{filename} =~ s:.*/::g;
181
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) };
187   }
188
189   return undef if $email_journal > 1 && !defined $attachment_content;
190
191   $attachment_content ||= ' ';
192   $attributes{charset}  = $self->{charset} if $self->{charset} && ($attributes{content_type} =~ m{^text/});
193
194   my $ent;
195   if ( $attributes{content_type} eq 'message/rfc822' ) {
196     $ent = Email::MIME->new($attachment_content);
197   } else {
198     $ent = Email::MIME->create(
199       attributes => \%attributes,
200       body       => $attachment_content,
201     );
202   }
203
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}) . '"');
210
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 : ' '),
215     file_id   => $file_id,
216   );
217
218   return $ent;
219 }
220
221 sub _create_message {
222   my ($self) = @_;
223
224   my @parts;
225
226   if ($self->{message}) {
227     push @parts, Email::MIME->create(
228       attributes => {
229         content_type => $self->{content_type},
230         charset      => $self->{charset},
231         encoding     => 'quoted-printable',
232       },
233       body_str => $self->{message},
234     );
235
236     push @{ $self->{headers} }, (
237       'Content-Type' => qq|$self->{content_type}; charset="$self->{charset}"|,
238     );
239   }
240
241   push @parts, grep { $_ } map { $self->_create_attachment_part($_) } @{ $self->{attachments} || [] };
242
243   return Email::MIME->create(
244       header_str => $self->{headers},
245       parts      => \@parts,
246   );
247 }
248
249 sub send {
250   my ($self) = @_;
251
252   # Create driver for delivery method (sendmail/SMTP)
253   $self->{driver} = eval { $self->_create_driver };
254   if (!$self->{driver}) {
255     my $error = $@;
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");
258
259     return $error;
260   }
261
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,
270   );
271   $self->{mail_attachments} = [];
272
273   my $error;
274   my $ok = eval {
275     # Clean up To/Cc/Bcc address fields
276     $self->_cleanup_addresses;
277     $self->_create_address_headers;
278
279     my $email = $self->_create_message;
280
281     my $from_obj = (Email::Address->parse($self->{from}))[0];
282
283     $self->{driver}->start_mail(from => $from_obj->address, to => [ $self->_all_recipients ]);
284     $self->{driver}->print($email->as_string);
285     $self->{driver}->send;
286
287     1;
288   };
289
290   $error = $@ if !$ok;
291
292   # create journal and link to record
293   $self->{journalentry} = $self->_store_in_journal;
294   $self->_create_record_link if $self->{journalentry};
295
296   return $ok ? '' : ($error || "undefined error");
297 }
298
299 sub _all_recipients {
300   my ($self) = @_;
301   $self->{addresses} ||= {};
302   return map { @{ $self->{addresses}->{$_} || [] } } qw(to cc bcc);
303 }
304
305 sub _store_in_journal {
306   my ($self, $status, $extended_status) = @_;
307
308   my $journal_enable = $::instance_conf->get_email_journal;
309
310   return if $journal_enable == 0;
311
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';
316
317   my $headers = join "\r\n", (bundle_by { join(': ', @_) } 2, @{ $self->{headers} || [] });
318
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} // '',
324     headers         => $headers,
325     body            => $self->{message} // '',
326     sent_on         => DateTime->now_local,
327     attachments     => \@{ $self->{mail_attachments} },
328     status          => $status,
329     extended_status => $extended_status,
330   )->save;
331   return $jentry->id;
332 }
333
334
335 sub _create_record_link {
336   my ($self) = @_;
337
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};
341
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(
345       mode       => 'ids',
346       from_table => $type_to_table{$record_type},
347       from_ids   => $record_id,
348       to_table   => 'email_journal',
349       to_id      => $self->{journalentry},
350     );
351   }
352 }
353
354 1;
355
356
357 __END__
358
359 =pod
360
361 =encoding utf8
362
363 =head1 NAME
364
365 SL::Mailer - Base class for sending mails from kivitendo
366
367 =head1 SYNOPSIS
368
369   package SL::BackgroundJob::CreatePeriodicInvoices;
370
371   use SL::Mailer;
372
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;
379
380   $mail->send;
381
382 =head1 OVERVIEW
383
384 Mail can be sent from kivitendo via the sendmail command or the smtp protocol.
385
386
387 =head1 INTERNAL DATA TYPES
388
389
390 =over 2
391
392 =item C<%mail_delivery_modules>
393
394   Currently two modules are supported: smtp or sendmail.
395
396 =item C<%type_to_table>
397
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
402   based object type.
403
404 =back
405
406 =head1 FUNCTIONS
407
408 =over 4
409
410 =item C<new>
411
412 =item C<_create_driver>
413
414 =item C<_cleanup_addresses>
415
416 =item C<_create_address_headers>
417
418 =item C<_create_message_id>
419
420 =item C<_create_attachment_part>
421
422 =item C<_create_message>
423
424 =item C<send>
425
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.
430
431 =item C<_all_recipients>
432
433 =item C<_store_in_journal>
434
435 =item C<_create_record_link $self->{journalentry}, $::form->{id}, $self->{record_id}>
436
437
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
442   the mail.
443   Will fail silently if record_link creation wasn't successful (same behaviour as
444   _store_in_journal).
445
446 =item C<validate>
447
448 =back
449
450 =head1 BUGS
451
452 Nothing here yet.
453
454 =head1 AUTHOR
455
456 =cut