Mailer: überflüssigen Nicht-Standard-Header entfernt
[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
33 use SL::Common;
34 use SL::DB::EmailJournal;
35 use SL::DB::EmailJournalAttachment;
36 use SL::DB::Employee;
37 use SL::Template;
38 use SL::Version;
39
40 use strict;
41
42 my $num_sent = 0;
43
44 my %mail_delivery_modules = (
45   sendmail => 'SL::Mailer::Sendmail',
46   smtp     => 'SL::Mailer::SMTP',
47 );
48
49 my %type_to_table = (
50   sales_quotation         => 'oe',
51   request_quotation       => 'oe',
52   sales_order             => 'oe',
53   purchase_order          => 'oe',
54   invoice                 => 'ar',
55   credit_note             => 'ar',
56   purchase_invoice        => 'ap',
57   letter                  => 'letter',
58   purchase_delivery_order => 'delivery_orders',
59   sales_delivery_order    => 'delivery_orders',
60 );
61
62 sub new {
63   my ($type, %params) = @_;
64   my $self = { %params };
65
66   bless $self, $type;
67 }
68
69 sub _create_driver {
70   my ($self) = @_;
71
72   my %params = (
73     mailer   => $self,
74     form     => $::form,
75     myconfig => \%::myconfig,
76   );
77
78   my $module = $mail_delivery_modules{ $::lx_office_conf{mail_delivery}->{method} };
79   eval "require $module" or return undef;
80
81   return $module->new(%params);
82 }
83
84 sub _cleanup_addresses {
85   my ($self) = @_;
86
87   foreach my $item (qw(to cc bcc)) {
88     next unless $self->{$item};
89
90     $self->{$item} =~ s/\&lt;/</g;
91     $self->{$item} =~ s/\$<\$/</g;
92     $self->{$item} =~ s/\&gt;/>/g;
93     $self->{$item} =~ s/\$>\$/>/g;
94   }
95 }
96
97 sub _create_message_id {
98   my ($self) = @_;
99
100   $num_sent  +=  1;
101   my $domain  =  $self->{from};
102   $domain     =~ s/.*\@//;
103   $domain     =~ s/>.*//;
104
105   return  "kivitendo-" . SL::Version->get_version . "-" . time() . "-${$}-${num_sent}\@$domain";
106 }
107
108 sub _create_address_headers {
109   my ($self) = @_;
110
111   # $self->{addresses} collects the recipients for use in e.g. the
112   # SMTP 'RCPT TO:' envelope command. $self->{headers} collects the
113   # headers that make up the actual email. 'BCC' should not be
114   # included there for certain transportation methods (SMTP).
115
116   $self->{addresses} = {};
117
118   foreach my $item (qw(from to cc bcc)) {
119     $self->{addresses}->{$item} = [];
120     next if !$self->{$item};
121
122     my @header_addresses;
123
124     foreach my $addr_obj (Email::Address->parse($self->{$item})) {
125       push @{ $self->{addresses}->{$item} }, $addr_obj->address;
126       next if $self->{driver}->keep_from_header($item);
127
128       my $phrase = $addr_obj->phrase();
129       if ($phrase) {
130         $phrase =~ s/^\"//;
131         $phrase =~ s/\"$//;
132         $addr_obj->phrase($phrase);
133       }
134
135       push @header_addresses, $addr_obj->format;
136     }
137
138     push @{ $self->{headers} }, ( ucfirst($item) => join(', ', @header_addresses) ) if @header_addresses;
139   }
140 }
141
142 sub _create_attachment_part {
143   my ($self, $attachment) = @_;
144
145   my %attributes = (
146     disposition  => 'attachment',
147     encoding     => 'base64',
148   );
149
150   my $attachment_content;
151   my $file_id       = 0;
152   my $email_journal = $::instance_conf->get_email_journal;
153
154   if (ref($attachment) eq "HASH") {
155     $attributes{filename}     = $attachment->{name};
156     $file_id                  = $attachment->{id}   || '0';
157     $attributes{content_type} = $attachment->{type} || 'application/pdf';
158     $attachment_content       = $attachment->{content};
159     $attachment_content       = eval { read_file($attachment->{path}) } if !$attachment_content;
160
161   } else {
162     $attributes{filename} =  $attachment;
163     $attributes{filename} =~ s:.*\Q$self->{fileid}\E:: if $self->{fileid};
164     $attributes{filename} =~ s:.*/::g;
165
166     my $application             = ($attachment =~ /(^\w+$)|\.(html|text|txt|sql)$/) ? 'text' : 'application';
167     $attributes{content_type}   = File::MimeInfo::Magic::magic($attachment);
168     $attributes{content_type} ||= "${application}/$self->{format}" if $self->{format};
169     $attributes{content_type} ||= 'application/octet-stream';
170     $attachment_content         = eval { read_file($attachment) };
171   }
172
173   return undef if $email_journal > 1 && !defined $attachment_content;
174
175   $attachment_content ||= ' ';
176   $attributes{charset}  = $self->{charset} if $self->{charset} && ($attributes{content_type} =~ m{^text/});
177
178   my $ent;
179   if ( $attributes{content_type} eq 'message/rfc822' ) {
180     $ent = Email::MIME->new($attachment_content);
181   } else {
182     $ent = Email::MIME->create(
183       attributes => \%attributes,
184       body       => $attachment_content,
185     );
186   }
187
188   # Due to a bug in Email::MIME it's not enough to hand over the encoded file name in the "attributes" hash in the
189   # "create" call. Email::MIME iterates over the keys in the hash, and depending on which key it has already seen during
190   # the iteration it might revert the encoding. As Perl's hash key order is randomized for each Perl run, this means
191   # that the file name stays unencoded sometimes.
192   # Setting the header manually after the "create" call circumvents this problem.
193   $ent->header_set('Content-disposition' => 'attachment; filename="' . encode('MIME-Q', $attributes{filename}) . '"');
194
195   push @{ $self->{mail_attachments}} , SL::DB::EmailJournalAttachment->new(
196     name      => $attributes{filename},
197     mime_type => $attributes{content_type},
198     content   => ( $email_journal > 1 ? $attachment_content : ' '),
199     file_id   => $file_id,
200   );
201
202   return $ent;
203 }
204
205 sub _create_message {
206   my ($self) = @_;
207
208   my @parts;
209
210   if ($self->{message}) {
211     push @parts, Email::MIME->create(
212       attributes => {
213         content_type => $self->{content_type},
214         charset      => $self->{charset},
215         encoding     => 'quoted-printable',
216       },
217       body_str => $self->{message},
218     );
219
220     push @{ $self->{headers} }, (
221       'Content-Type' => qq|$self->{content_type}; charset="$self->{charset}"|,
222     );
223   }
224
225   push @parts, grep { $_ } map { $self->_create_attachment_part($_) } @{ $self->{attachments} || [] };
226
227   return Email::MIME->create(
228       header_str => $self->{headers},
229       parts      => \@parts,
230   );
231 }
232
233 sub send {
234   my ($self) = @_;
235
236   # Create driver for delivery method (sendmail/SMTP)
237   $self->{driver} = eval { $self->_create_driver };
238   if (!$self->{driver}) {
239     my $error = $@;
240     $self->_store_in_journal('failed', 'driver could not be created; check your configuration & log files');
241     $::lxdebug->message(LXDebug::WARN(), "Mailer error during 'send': $error");
242
243     return $error;
244   }
245
246   # Set defaults & headers
247   $self->{charset}        =  'UTF-8';
248   $self->{content_type} ||=  "text/plain";
249   $self->{headers}      ||=  [];
250   push @{ $self->{headers} }, (
251     Subject               => $self->{subject},
252     'Message-ID'          => '<' . $self->_create_message_id . '>',
253     'X-Mailer'            => "kivitendo " . SL::Version->get_version,
254   );
255   $self->{mail_attachments} = [];
256   $self->{content_by_name}  = $::instance_conf->get_email_journal == 1 && $::instance_conf->get_doc_files;
257
258   my $error;
259   my $ok = eval {
260     # Clean up To/Cc/Bcc address fields
261     $self->_cleanup_addresses;
262     $self->_create_address_headers;
263
264     my $email = $self->_create_message;
265
266     my $from_obj = (Email::Address->parse($self->{from}))[0];
267
268     $self->{driver}->start_mail(from => $from_obj->address, to => [ $self->_all_recipients ]);
269     $self->{driver}->print($email->as_string);
270     $self->{driver}->send;
271
272     1;
273   };
274
275   $error = $@ if !$ok;
276
277   # create journal and link to record
278   $self->{journalentry} = $self->_store_in_journal;
279   $self->_create_record_link if $self->{journalentry};
280
281   return $ok ? '' : ($error || "undefined error");
282 }
283
284 sub _all_recipients {
285   my ($self) = @_;
286   $self->{addresses} ||= {};
287   return map { @{ $self->{addresses}->{$_} || [] } } qw(to cc bcc);
288 }
289
290 sub _store_in_journal {
291   my ($self, $status, $extended_status) = @_;
292
293   my $journal_enable = $::instance_conf->get_email_journal;
294
295   return if $journal_enable == 0;
296
297   $status          //= $self->{driver}->status if $self->{driver};
298   $status          //= 'failed';
299   $extended_status //= $self->{driver}->extended_status if $self->{driver};
300   $extended_status //= 'unknown error';
301
302   my $headers = join "\r\n", (bundle_by { join(': ', @_) } 2, @{ $self->{headers} || [] });
303
304   my $jentry = SL::DB::EmailJournal->new(
305     sender          => SL::DB::Manager::Employee->current,
306     from            => $self->{from}    // '',
307     recipients      => join(', ', $self->_all_recipients),
308     subject         => $self->{subject} // '',
309     headers         => $headers,
310     body            => $self->{message} // '',
311     sent_on         => DateTime->now_local,
312     attachments     => \@{ $self->{mail_attachments} },
313     status          => $status,
314     extended_status => $extended_status,
315   )->save;
316   return $jentry->id;
317 }
318
319
320 sub _create_record_link {
321   my ($self) = @_;
322
323   # check for custom/overloaded types and ids (form != controller)
324   my $record_type = $self->{record_type} || $::form->{type};
325   my $record_id   = $self->{record_id}   || $::form->{id};
326
327   # you may send mails for unsaved objects (no record_id => unlinkable case)
328   if ($self->{journalentry} && $record_id && exists($type_to_table{$record_type})) {
329     RecordLinks->create_links(
330       mode       => 'ids',
331       from_table => $type_to_table{$record_type},
332       from_ids   => $record_id,
333       to_table   => 'email_journal',
334       to_id      => $self->{journalentry},
335     );
336   }
337 }
338
339 1;
340
341
342 __END__
343
344 =pod
345
346 =encoding utf8
347
348 =head1 NAME
349
350 SL::Mailer - Base class for sending mails from kivitendo
351
352 =head1 SYNOPSIS
353
354   package SL::BackgroundJob::CreatePeriodicInvoices;
355
356   use SL::Mailer;
357
358   my $mail              = Mailer->new;
359   $mail->{from}         = $config{periodic_invoices}->{email_from};
360   $mail->{to}           = $email;
361   $mail->{subject}      = $config{periodic_invoices}->{email_subject};
362   $mail->{content_type} = $filename =~ m/.html$/ ? 'text/html' : 'text/plain';
363   $mail->{message}      = $output;
364
365   $mail->send;
366
367 =head1 OVERVIEW
368
369 Mail can be sent from kivitendo via the sendmail command or the smtp protocol.
370
371
372 =head1 INTERNAL DATA TYPES
373
374
375 =over 2
376
377 =item C<%mail_delivery_modules>
378
379   Currently two modules are supported: smtp or sendmail.
380
381 =item C<%type_to_table>
382
383   Due to the lack of a single global mapping for $form->{type},
384   type is mapped to the corresponding database table. All types which
385   implement a mail action are currently mapped and should be mapped.
386   Type is either the value of the old form or the newer controller
387   based object type.
388
389 =back
390
391 =head1 FUNCTIONS
392
393 =over 4
394
395 =item C<new>
396
397 =item C<_create_driver>
398
399 =item C<_cleanup_addresses>
400
401 =item C<_create_address_headers>
402
403 =item C<_create_message_id>
404
405 =item C<_create_attachment_part>
406
407 =item C<_create_message>
408
409 =item C<send>
410
411   If a mail was sent successfully the internal function _store_in_journal
412   is called if email journaling is enabled. If _store_in_journal was executed
413   successfully and the calling form is already persistent (database id) a
414   record_link will be created.
415
416 =item C<_all_recipients>
417
418 =item C<_store_in_journal>
419
420 =item C<_create_record_link $self->{journalentry}, $::form->{id}, $self->{record_id}>
421
422
423   If $self->{journalentry} and either $self->{record_id} or $::form->{id} (checked in
424   this order) exist a record link from record to email journal is created.
425   Will fail silently if record_link creation wasn't successful (same behaviour as
426   _store_in_journal).
427
428 =item C<validate>
429
430 =back
431
432 =head1 BUGS
433
434 Nothing here yet.
435
436 =head1 AUTHOR
437
438 =cut