E-Mail: Versandfehler oben auch anzeigen
[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 File::MimeInfo::Magic;
29 use File::Slurp;
30 use List::UtilsBy qw(bundle_by);
31
32 use SL::Common;
33 use SL::DB::EmailJournal;
34 use SL::DB::EmailJournalAttachment;
35 use SL::DB::Employee;
36 use SL::Template;
37
38 use strict;
39
40 my $num_sent = 0;
41
42 my %mail_delivery_modules = (
43   sendmail => 'SL::Mailer::Sendmail',
44   smtp     => 'SL::Mailer::SMTP',
45 );
46
47 sub new {
48   my ($type, %params) = @_;
49   my $self = { %params };
50
51   bless $self, $type;
52 }
53
54 sub _create_driver {
55   my ($self) = @_;
56
57   my %params = (
58     mailer   => $self,
59     form     => $::form,
60     myconfig => \%::myconfig,
61   );
62
63   my $module = $mail_delivery_modules{ $::lx_office_conf{mail_delivery}->{method} };
64   eval "require $module" or return undef;
65
66   return $module->new(%params);
67 }
68
69 sub _cleanup_addresses {
70   my ($self) = @_;
71
72   foreach my $item (qw(to cc bcc)) {
73     next unless $self->{$item};
74
75     $self->{$item} =~ s/\&lt;/</g;
76     $self->{$item} =~ s/\$<\$/</g;
77     $self->{$item} =~ s/\&gt;/>/g;
78     $self->{$item} =~ s/\$>\$/>/g;
79   }
80 }
81
82 sub _create_message_id {
83   my ($self) = @_;
84
85   $num_sent  +=  1;
86   my $domain  =  $self->{from};
87   $domain     =~ s/.*\@//;
88   $domain     =~ s/>.*//;
89
90   return  "kivitendo-$self->{version}-" . time() . "-${$}-${num_sent}\@$domain";
91 }
92
93 sub _create_address_headers {
94   my ($self) = @_;
95
96   # $self->{addresses} collects the recipients for use in e.g. the
97   # SMTP 'RCPT TO:' envelope command. $self->{headers} collects the
98   # headers that make up the actual email. 'BCC' should not be
99   # included there for certain transportation methods (SMTP).
100
101   $self->{addresses} = {};
102
103   foreach my $item (qw(from to cc bcc)) {
104     $self->{addresses}->{$item} = [];
105     next if !$self->{$item};
106
107     my @header_addresses;
108
109     foreach my $addr_obj (Email::Address->parse($self->{$item})) {
110       push @{ $self->{addresses}->{$item} }, $addr_obj->address;
111       next if $self->{driver}->keep_from_header($item);
112
113       my $phrase = $addr_obj->phrase();
114       if ($phrase) {
115         $phrase =~ s/^\"//;
116         $phrase =~ s/\"$//;
117         $addr_obj->phrase($phrase);
118       }
119
120       push @header_addresses, $addr_obj->format;
121     }
122
123     push @{ $self->{headers} }, ( ucfirst($item) => join(', ', @header_addresses) ) if @header_addresses;
124   }
125 }
126
127 sub _create_attachment_part {
128   my ($self, $attachment) = @_;
129
130   my %attributes = (
131     disposition  => 'attachment',
132     encoding     => 'base64',
133   );
134
135   my $attachment_content;
136   my $file_id       = 0;
137   my $email_journal = $::instance_conf->get_email_journal;
138
139   $::lxdebug->message(LXDebug->DEBUG2(), "mail5 att=" . $attachment . " email_journal=" . $email_journal . " id=" . $attachment->{id});
140
141   if (ref($attachment) eq "HASH") {
142     $attributes{filename}     = $attachment->{name};
143     $file_id                  = $attachment->{id}   || '0';
144     $attributes{content_type} = $attachment->{type} || 'application/pdf';
145     $attachment_content       = $attachment->{content};
146     $attachment_content       = eval { read_file($attachment->{path}) } if !$attachment_content;
147
148   } else {
149     $attributes{filename} =  $attachment;
150     $attributes{filename} =~ s:.*\Q$self->{fileid}\E:: if $self->{fileid};
151     $attributes{filename} =~ s:.*/::g;
152
153     my $application             = ($attachment =~ /(^\w+$)|\.(html|text|txt|sql)$/) ? 'text' : 'application';
154     $attributes{content_type}   = File::MimeInfo::Magic::magic($attachment);
155     $attributes{content_type} ||= "${application}/$self->{format}" if $self->{format};
156     $attributes{content_type} ||= 'application/octet-stream';
157     $attachment_content         = eval { read_file($attachment) };
158   }
159
160   return undef if $email_journal > 1 && !defined $attachment_content;
161
162   $attachment_content ||= ' ';
163   $attributes{charset}  = $self->{charset} if $self->{charset} && ($attributes{content_type} =~ m{^text/});
164
165   $::lxdebug->message(LXDebug->DEBUG2(), "mail6 mtype=" . $attributes{content_type} . " filename=" . $attributes{filename});
166
167   my $ent;
168   if ( $attributes{content_type} eq 'message/rfc822' ) {
169     $ent = Email::MIME->new($attachment_content);
170     $ent->header_str_set('Content-disposition' => 'attachment; filename='.$attributes{filename});
171   } else {
172     $ent = Email::MIME->create(
173       attributes => \%attributes,
174       body       => $attachment_content,
175     );
176   }
177
178   push @{ $self->{mail_attachments}} , SL::DB::EmailJournalAttachment->new(
179     name      => $attributes{filename},
180     mime_type => $attributes{content_type},
181     content   => ( $email_journal > 1 ? $attachment_content : ' '),
182     file_id   => $file_id,
183   );
184
185   return $ent;
186 }
187
188 sub _create_message {
189   my ($self) = @_;
190
191   my @parts;
192
193   push @{ $self->{headers} }, (Type => "multipart/mixed");
194
195   if ($self->{message}) {
196     push @parts, Email::MIME->create(
197       attributes => {
198         content_type => $self->{contenttype},
199         charset      => $self->{charset},
200         encoding     => 'quoted-printable',
201       },
202       body_str => $self->{message},
203     );
204
205     push @{ $self->{headers} }, (
206       'Content-Type' => qq|$self->{contenttype}; charset="$self->{charset}"|,
207     );
208   }
209
210   push @parts, grep { $_ } map { $self->_create_attachment_part($_) } @{ $self->{attachments} || [] };
211
212   return Email::MIME->create(
213       header_str => $self->{headers},
214       parts      => \@parts,
215   );
216 }
217
218 sub send {
219   my ($self) = @_;
220
221   # Create driver for delivery method (sendmail/SMTP)
222   $self->{driver} = eval { $self->_create_driver };
223   if (!$self->{driver}) {
224     my $error = $@;
225     $self->_store_in_journal('failed', 'driver could not be created; check your configuration & log files');
226     $::lxdebug->message(LXDebug::WARN(), "Mailer error during 'send': $error");
227
228     return $error;
229   }
230
231   # Set defaults & headers
232   $self->{charset}       =  'UTF-8';
233   $self->{contenttype} ||=  "text/plain";
234   $self->{headers}       =  [
235     Subject              => $self->{subject},
236     'Message-ID'         => '<' . $self->_create_message_id . '>',
237     'X-Mailer'           => "kivitendo $self->{version}",
238   ];
239   $self->{mail_attachments} = [];
240   $self->{content_by_name}  = $::instance_conf->get_email_journal == 1 && $::instance_conf->get_doc_files;
241
242   my $error;
243   my $ok = eval {
244     # Clean up To/Cc/Bcc address fields
245     $self->_cleanup_addresses;
246     $self->_create_address_headers;
247
248     my $email = $self->_create_message;
249
250     #$::lxdebug->message(0, "message: " . $email->as_string);
251     # return "boom";
252
253     $::lxdebug->message(LXDebug->DEBUG2(), "mail1 from=".$self->{from}." to=".$self->{to});
254     my $from_obj = (Email::Address->parse($self->{from}))[0];
255
256     $self->{driver}->start_mail(from => $from_obj->address, to => [ $self->_all_recipients ]);
257     $self->{driver}->print($email->as_string);
258     $self->{driver}->send;
259
260     1;
261   };
262
263   $error = $@ if !$ok;
264
265   $self->{journalentry} = $self->_store_in_journal;
266
267   return $ok ? '' : ($error || "undefined error");
268 }
269
270 sub _all_recipients {
271   my ($self) = @_;
272   $self->{addresses} ||= {};
273   return map { @{ $self->{addresses}->{$_} || [] } } qw(to cc bcc);
274 }
275
276 sub _store_in_journal {
277   my ($self, $status, $extended_status) = @_;
278
279   my $journal_enable = $::instance_conf->get_email_journal;
280
281   return if $journal_enable == 0;
282
283   $status          //= $self->{driver}->status if $self->{driver};
284   $status          //= 'failed';
285   $extended_status //= $self->{driver}->extended_status if $self->{driver};
286   $extended_status //= 'unknown error';
287
288   my $headers = join "\r\n", (bundle_by { join(': ', @_) } 2, @{ $self->{headers} || [] });
289
290   my $jentry = SL::DB::EmailJournal->new(
291     sender          => SL::DB::Manager::Employee->current,
292     from            => $self->{from}    // '',
293     recipients      => join(', ', $self->_all_recipients),
294     subject         => $self->{subject} // '',
295     headers         => $headers,
296     body            => $self->{message} // '',
297     sent_on         => DateTime->now_local,
298     attachments     => \@{ $self->{mail_attachments} },
299     status          => $status,
300     extended_status => $extended_status,
301   )->save;
302   return $jentry->id;
303 }
304
305 1;