SL::Mailer: Kosmetik für bessere Lesbarkeit (Alignment, Leerzeichen, Einrückung)
[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 $attachment_content;
141   my $file_id       = 0;
142   my $email_journal = $::instance_conf->get_email_journal;
143
144   $::lxdebug->message(LXDebug->DEBUG2(), "mail5 att=" . $attachment . " email_journal=" . $email_journal . " id=" . $attachment->{id});
145
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;
152
153   } else {
154     # strip path
155     $attributes{Path}     =  $attachment;
156     $attributes{Filename} =  $attachment;
157     $attributes{Filename} =~ s:.*\Q$self->{fileid}\E:: if $self->{fileid};
158     $attributes{Filename} =~ s:.*/::g;
159
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;
165   }
166
167   return undef if $email_journal > 1 && !defined $attachment_content;
168
169   $attachment_content ||= ' ';
170   $attributes{Charset}  = $self->{charset} if $self->{charset};
171
172   $::lxdebug->message(LXDebug->DEBUG2(), "mail6 mtype=" . $attributes{Type} . " path=" . $attributes{Path} . " filename=" . $attributes{Filename});
173
174   my $ent;
175   if ( $attributes{Type} eq 'message/rfc822' ) {
176     my $fh = IO::File->new($attributes{Path}, "r") or return undef;
177     $ent   = $parser->parse($fh);
178
179     $ent->head->replace('Content-disposition','attachment; filename='.$attributes{Filename});
180
181   } else {
182     $ent = MIME::Entity->build(%attributes);
183   }
184
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 : ' '),
189     file_id   => $file_id,
190   );
191
192   return $ent;
193 }
194
195 sub _create_message {
196   my ($self) = @_;
197
198   push @{ $self->{headers} }, (Type => "multipart/mixed");
199
200   my $top = MIME::Entity->build(@{$self->{headers}});
201
202   if ($self->{message}) {
203     $top->attach(
204       Data     => encode($self->{charset},$self->{message}),
205       Charset  => $self->{charset},
206       Type     => $self->{contenttype},
207       Encoding => 'quoted-printable',
208     );
209   }
210
211   $top->add_part($self->_create_attachment_part($_)) for @{ $self->{attachments} || [] };
212
213   return $top;
214 }
215
216 sub send {
217   my ($self) = @_;
218
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 : $@";
224   }
225
226   # Set defaults & headers
227   $self->{charset}       =  'UTF-8';
228   $self->{contenttype} ||=  "text/plain";
229   $self->{headers}       =  [
230     Subject              => encode('MIME-Header',$self->{subject}),
231     'Message-ID'         => '<' . $self->_create_message_id . '>',
232     'X-Mailer'           => "kivitendo $self->{version}",
233   ];
234   $self->{mail_attachments} = [];
235   $self->{content_by_name}  = $::instance_conf->get_email_journal == 1 && $::instance_conf->get_doc_files;
236
237   my $error;
238   my $ok = eval {
239     # Clean up To/Cc/Bcc address fields
240     $self->_cleanup_addresses;
241     $self->_create_address_headers;
242
243     my $email = $self->_create_message;
244
245     #$::lxdebug->message(0, "message: " . $email->as_string);
246     # return "boom";
247
248     $self->{driver}->start_mail(from => encode('MIME-Header',$self->{from}), to => [ $self->_all_recipients ]);
249     $self->{driver}->print($email->as_string);
250     $self->{driver}->send;
251
252     1;
253   };
254
255   $error = $@ if !$ok;
256
257   $self->{journalentry} = $self->_store_in_journal;
258   $parser->filer->purge;
259
260   return $ok ? '' : "send email: $error";
261 }
262
263 sub _all_recipients {
264   my ($self) = @_;
265   $self->{addresses} ||= {};
266   return map { @{ $self->{addresses}->{$_} || [] } } qw(to cc bcc);
267 }
268
269 sub _store_in_journal {
270   my ($self, $status, $extended_status) = @_;
271
272   my $journal_enable = $::instance_conf->get_email_journal;
273
274   return if $journal_enable == 0;
275
276   $status          //= $self->{driver}->status if $self->{driver};
277   $status          //= 'failed';
278   $extended_status //= $self->{driver}->extended_status if $self->{driver};
279   $extended_status //= 'unknown error';
280
281   my $headers = join "\r\n", (bundle_by { join(': ', @_) } 2, @{ $self->{headers} || [] });
282
283   my $jentry = SL::DB::EmailJournal->new(
284     sender          => SL::DB::Manager::Employee->current,
285     from            => $self->{from}    // '',
286     recipients      => join(', ', $self->_all_recipients),
287     subject         => $self->{subject} // '',
288     headers         => $headers,
289     body            => $self->{message} // '',
290     sent_on         => DateTime->now_local,
291     attachments     => \@{ $self->{mail_attachments} },
292     status          => $status,
293     extended_status => $extended_status,
294   )->save;
295   return $jentry->id;
296 }
297
298 1;