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