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