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