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