E-Mail-Journal: verschickte E-Mails speichern
[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 $source_file_name;
125
126   my %attributes = (
127     disposition  => 'attachment',
128     encoding     => 'base64',
129   );
130
131   if (ref($attachment) eq "HASH") {
132     $attributes{filename} = $attachment->{name};
133     $source_file_name     = $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     $source_file_name     =  $attachment;
141   }
142
143   my $attachment_content = eval { read_file($source_file_name) };
144   return undef if !defined $attachment_content;
145
146   my $application             = ($attachment =~ /(^\w+$)|\.(html|text|txt|sql)$/) ? 'text' : 'application';
147   $attributes{content_type}   = SL::MIME->mime_type_from_ext($attributes{filename});
148   $attributes{content_type} ||= "${application}/$self->{format}" if $self->{format};
149   $attributes{content_type} ||= 'application/octet-stream';
150   $attributes{charset}        = $self->{charset} if lc $application eq 'text' && $self->{charset};
151
152   return Email::MIME->create(
153     attributes => \%attributes,
154     body       => $attachment_content,
155   );
156 }
157
158 sub _create_message {
159   my ($self) = @_;
160
161   my @parts;
162
163   if ($self->{message}) {
164     push @parts, Email::MIME->create(
165       attributes => {
166         content_type => $self->{contenttype},
167         charset      => $self->{charset},
168         encoding     => 'quoted-printable',
169       },
170       body_str => $self->{message},
171     );
172
173     push @{ $self->{headers} }, (
174       'Content-Type' => qq|$self->{contenttype}; charset="$self->{charset}"|,
175     );
176   }
177
178   push @parts, grep { $_ } map { $self->_create_attachment_part($_) } @{ $self->{attachments} || [] };
179
180   return Email::MIME->create(
181     header_str => $self->{headers},
182     parts      => \@parts,
183   );
184 }
185
186 sub send {
187   my ($self) = @_;
188
189   # Create driver for delivery method (sendmail/SMTP)
190   $self->{driver} = eval { $self->_create_driver };
191   if (!$self->{driver}) {
192     $self->_store_in_journal('failed', 'driver could not be created; check your configuration');
193     return "send email : $@";
194   }
195
196   # Set defaults & headers
197   $self->{charset}       =  'UTF-8';
198   $self->{contenttype} ||=  "text/plain";
199   $self->{headers}       =  [
200     Subject              => $self->{subject},
201     'Message-ID'         => '<' . $self->_create_message_id . '>',
202     'X-Mailer'           => "kivitendo $self->{version}",
203   ];
204
205   my $error;
206   my $ok = eval {
207     # Clean up To/Cc/Bcc address fields
208     $self->_cleanup_addresses;
209     $self->_create_address_headers;
210
211     my $email = $self->_create_message;
212
213     # $::lxdebug->message(0, "message: " . $email->as_string);
214     # return "boom";
215
216     $self->{driver}->start_mail(from => $self->{from}, to => [ $self->_all_recipients ]);
217     $self->{driver}->print($email->as_string);
218     $self->{driver}->send;
219
220     1;
221   };
222
223   $error = $@ if !$ok;
224
225   $self->_store_in_journal;
226
227   return $ok ? '' : "send email: $error";
228 }
229
230 sub _all_recipients {
231   my ($self) = @_;
232
233   $self->{addresses} ||= {};
234   return map { @{ $self->{addresses}->{$_} || [] } } qw(to cc bcc);
235 }
236
237 sub _store_in_journal {
238   my ($self, $status, $extended_status) = @_;
239
240   $status          //= $self->{driver}->status if $self->{driver};
241   $status          //= 'failed';
242   $extended_status //= $self->{driver}->extended_status if $self->{driver};
243   $extended_status //= 'unknown error';
244
245   my @attachments = grep { $_ } map {
246     my $part = $self->_create_attachment_part($_);
247     if ($part) {
248       SL::DB::EmailJournalAttachment->new(
249         name      => $part->filename,
250         mime_type => $part->content_type,
251         content   => $part->body,
252       )
253     }
254   } @{ $self->{attachments} || [] };
255
256   my $headers = join "\r\n", (bundle_by { join(': ', @_) } 2, @{ $self->{headers} || [] });
257
258   SL::DB::EmailJournal->new(
259     sender          => SL::DB::Manager::Employee->current,
260     from            => $self->{from}    // '',
261     recipients      => join(', ', $self->_all_recipients),
262     subject         => $self->{subject} // '',
263     headers         => $headers,
264     body            => $self->{message} // '',
265     sent_on         => DateTime->now_local,
266     attachments     => \@attachments,
267     status          => $status,
268     extended_status => $extended_status,
269   )->save;
270 }
271
272 1;