Lx-Office durch kivitendo ersetzt
[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 # SQL-Ledger Accounting
9 # Copyright (C) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 # Contributors:
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
30
31 package Mailer;
32
33 use Email::Address;
34 use Encode;
35
36 use SL::Common;
37 use SL::MIME;
38 use SL::Template;
39
40 use strict;
41
42 my $num_sent = 0;
43
44 sub new {
45   $main::lxdebug->enter_sub();
46
47   my ($type, %params) = @_;
48   my $self = { %params };
49
50   $main::lxdebug->leave_sub();
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 $cfg = $::lx_office_conf{mail_delivery};
65   if (($cfg->{method} || 'smtp') ne 'smtp') {
66     require SL::Mailer::Sendmail;
67     return SL::Mailer::Sendmail->new(%params);
68   } else {
69     require SL::Mailer::SMTP;
70     return SL::Mailer::SMTP->new(%params);
71   }
72 }
73
74 sub mime_quote_text {
75   $main::lxdebug->enter_sub();
76
77   my ($self, $text, $chars_left) = @_;
78
79   my $q_start = "=?$self->{charset}?Q?";
80   my $l_start = length($q_start);
81
82   my $new_text = "$q_start";
83   $chars_left -= $l_start if (defined $chars_left);
84
85   for (my $i = 0; $i < length($text); $i++) {
86     my $char = ord(substr($text, $i, 1));
87
88     if (($char < 32) || ($char > 127) || ($char == ord('?')) || ($char == ord('_'))) {
89       if ((defined $chars_left) && ($chars_left < 5)) {
90         $new_text .= "?=\n $q_start";
91         $chars_left = 75 - $l_start;
92       }
93
94       $new_text .= sprintf("=%02X", $char);
95       $chars_left -= 3 if (defined $chars_left);
96
97     } else {
98       $char = ord('_') if ($char == ord(' '));
99       if ((defined $chars_left) && ($chars_left < 5)) {
100         $new_text .= "?=\n $q_start";
101         $chars_left = 75 - $l_start;
102       }
103
104       $new_text .= chr($char);
105       $chars_left-- if (defined $chars_left);
106     }
107   }
108
109   $new_text .= "?=";
110
111   $main::lxdebug->leave_sub();
112
113   return $new_text;
114 }
115
116 sub send {
117   $main::lxdebug->enter_sub();
118
119   my ($self) = @_;
120
121   local (*IN);
122
123   $num_sent++;
124   my $boundary    = time() . "-$$-${num_sent}";
125   $boundary       =  "kivitendo-$self->{version}-$boundary";
126   my $domain      =  $self->recode($self->{from});
127   $domain         =~ s/(.*?\@|>)//g;
128   my $msgid       =  "$boundary\@$domain";
129
130   my $form        =  $main::form;
131   my $myconfig    =  \%main::myconfig;
132
133   my $driver = eval { $self->_create_driver };
134   if (!$driver) {
135     $main::lxdebug->leave_sub();
136     return "send email : $@";
137   }
138
139   $self->{charset}     ||= Common::DEFAULT_CHARSET;
140   $self->{contenttype} ||= "text/plain";
141
142   foreach my $item (qw(to cc bcc)) {
143     next unless ($self->{$item});
144     $self->{$item} =  $self->recode($self->{$item});
145     $self->{$item} =~ s/\&lt;/</g;
146     $self->{$item} =~ s/\$<\$/</g;
147     $self->{$item} =~ s/\&gt;/>/g;
148     $self->{$item} =~ s/\$>\$/>/g;
149   }
150
151   $self->{from} = $self->recode($self->{from});
152
153   my %addresses;
154   my $headers = '';
155   foreach my $item (qw(from to cc bcc)) {
156     $addresses{$item} = [];
157     next unless ($self->{$item});
158
159     my (@addr_objects) = Email::Address->parse($self->{$item});
160     next unless (scalar @addr_objects);
161
162     foreach my $addr_obj (@addr_objects) {
163       push @{ $addresses{$item} }, $addr_obj->address;
164       my $phrase = $addr_obj->phrase();
165       if ($phrase) {
166         $phrase =~ s/^\"//;
167         $phrase =~ s/\"$//;
168         $addr_obj->phrase($self->mime_quote_text($phrase));
169       }
170
171       $headers .= sprintf("%s: %s\n", ucfirst($item), $addr_obj->format()) unless $driver->keep_from_header($item);
172     }
173   }
174
175   $headers .= sprintf("Subject: %s\n", $self->mime_quote_text($self->recode($self->{subject}), 60));
176
177   $driver->start_mail(from => $self->{from}, to => [ map { @{ $addresses{$_} } } qw(to cc bcc) ]);
178
179   $driver->print(qq|${headers}Message-ID: <$msgid>
180 X-Mailer: kivitendo $self->{version}
181 MIME-Version: 1.0
182 |);
183
184   if ($self->{attachments}) {
185     $driver->print(qq|Content-Type: multipart/mixed; boundary="$boundary"\n\n|);
186     if ($self->{message}) {
187       $driver->print(qq|--${boundary}
188 Content-Type: $self->{contenttype}; charset="$self->{charset}"
189
190 | . $self->recode($self->{message}) . qq|
191
192 |);
193     }
194
195     foreach my $attachment (@{ $self->{attachments} }) {
196
197       my $filename;
198
199       if (ref($attachment) eq "HASH") {
200         $filename = $attachment->{"name"};
201         $attachment = $attachment->{"filename"};
202       } else {
203         $filename = $attachment;
204         # strip path
205         $filename =~ s/(.*\/|\Q$self->{fileid}\E)//g;
206       }
207
208       my $application    = ($attachment =~ /(^\w+$)|\.(html|text|txt|sql)$/) ? "text" : "application";
209       my $content_type   = SL::MIME->mime_type_from_ext($filename);
210       $content_type      = "${application}/$self->{format}" if (!$content_type && $self->{format});
211       $content_type    ||= 'application/octet-stream';
212
213       open(IN, $attachment);
214       if ($?) {
215         $main::lxdebug->leave_sub();
216         return "$attachment : $!";
217       }
218
219       # only set charset for attachements of type text. every other type should not have this field
220       # refer to bug 883 for detailed information
221       my $attachment_charset;
222       if (lc $application eq 'text' && $self->{charset}) {
223         $attachment_charset = qq|; charset="$self->{charset}" |;
224       }
225
226       $driver->print(qq|--${boundary}
227 Content-Type: ${content_type}; name="$filename"$attachment_charset
228 Content-Transfer-Encoding: BASE64
229 Content-Disposition: attachment; filename="$filename"\n\n|);
230
231       my $msg = "";
232       while (<IN>) {
233         ;
234         $msg .= $_;
235       }
236       $driver->print(encode_base64($msg));
237
238       close(IN);
239
240     }
241     $driver->print(qq|--${boundary}--\n|);
242
243   } else {
244     $driver->print(qq|Content-Type: $self->{contenttype}; charset="$self->{charset}"
245
246 | . $self->recode($self->{message}) . qq|
247 |);
248   }
249
250   $driver->send;
251
252   $main::lxdebug->leave_sub();
253
254   return "";
255 }
256
257 sub encode_base64 ($;$) {
258   $main::lxdebug->enter_sub();
259
260   # this code is from the MIME-Base64-2.12 package
261   # Copyright 1995-1999,2001 Gisle Aas <gisle@ActiveState.com>
262
263   my $res = "";
264   my $eol = $_[1];
265   $eol = "\n" unless defined $eol;
266   pos($_[0]) = 0;    # ensure start at the beginning
267
268   $res = join '', map(pack('u', $_) =~ /^.(\S*)/, ($_[0] =~ /(.{1,45})/gs));
269
270   $res =~ tr|` -_|AA-Za-z0-9+/|;    # `# help emacs
271                                     # fix padding at the end
272   my $padding = (3 - length($_[0]) % 3) % 3;
273   $res =~ s/.{$padding}$/'=' x $padding/e if $padding;
274
275   # break encoded string into lines of no more than 60 characters each
276   if (length $eol) {
277     $res =~ s/(.{1,60})/$1$eol/g;
278   }
279
280   $main::lxdebug->leave_sub();
281
282   return $res;
283 }
284
285 sub recode {
286   my $self = shift;
287   my $text = shift;
288
289   return $::locale->is_utf8 ? Encode::encode('utf-8-strict', $text) : $text;
290 }
291
292 1;