1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
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.
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,
22 #======================================================================
27 use Email::MIME::Creator;
28 use File::MimeInfo::Magic;
30 use List::UtilsBy qw(bundle_by);
33 use SL::DB::EmailJournal;
34 use SL::DB::EmailJournalAttachment;
43 my %mail_delivery_modules = (
44 sendmail => 'SL::Mailer::Sendmail',
45 smtp => 'SL::Mailer::SMTP',
49 my ($type, %params) = @_;
50 my $self = { %params };
61 myconfig => \%::myconfig,
64 my $module = $mail_delivery_modules{ $::lx_office_conf{mail_delivery}->{method} };
65 eval "require $module" or return undef;
67 return $module->new(%params);
70 sub _cleanup_addresses {
73 foreach my $item (qw(to cc bcc)) {
74 next unless $self->{$item};
76 $self->{$item} =~ s/\</</g;
77 $self->{$item} =~ s/\$<\$/</g;
78 $self->{$item} =~ s/\>/>/g;
79 $self->{$item} =~ s/\$>\$/>/g;
83 sub _create_message_id {
87 my $domain = $self->{from};
91 return "kivitendo-" . SL::Version->get_version . "-" . time() . "-${$}-${num_sent}\@$domain";
94 sub _create_address_headers {
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).
102 $self->{addresses} = {};
104 foreach my $item (qw(from to cc bcc)) {
105 $self->{addresses}->{$item} = [];
106 next if !$self->{$item};
108 my @header_addresses;
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);
114 my $phrase = $addr_obj->phrase();
118 $addr_obj->phrase($phrase);
121 push @header_addresses, $addr_obj->format;
124 push @{ $self->{headers} }, ( ucfirst($item) => join(', ', @header_addresses) ) if @header_addresses;
128 sub _create_attachment_part {
129 my ($self, $attachment) = @_;
132 disposition => 'attachment',
133 encoding => 'base64',
136 my $attachment_content;
138 my $email_journal = $::instance_conf->get_email_journal;
140 $::lxdebug->message(LXDebug->DEBUG2(), "mail5 att=" . $attachment . " email_journal=" . $email_journal . " id=" . $attachment->{id});
142 if (ref($attachment) eq "HASH") {
143 $attributes{filename} = $attachment->{name};
144 $file_id = $attachment->{id} || '0';
145 $attributes{content_type} = $attachment->{type} || 'application/pdf';
146 $attachment_content = $attachment->{content};
147 $attachment_content = eval { read_file($attachment->{path}) } if !$attachment_content;
150 $attributes{filename} = $attachment;
151 $attributes{filename} =~ s:.*\Q$self->{fileid}\E:: if $self->{fileid};
152 $attributes{filename} =~ s:.*/::g;
154 my $application = ($attachment =~ /(^\w+$)|\.(html|text|txt|sql)$/) ? 'text' : 'application';
155 $attributes{content_type} = File::MimeInfo::Magic::magic($attachment);
156 $attributes{content_type} ||= "${application}/$self->{format}" if $self->{format};
157 $attributes{content_type} ||= 'application/octet-stream';
158 $attachment_content = eval { read_file($attachment) };
161 return undef if $email_journal > 1 && !defined $attachment_content;
163 $attachment_content ||= ' ';
164 $attributes{charset} = $self->{charset} if $self->{charset} && ($attributes{content_type} =~ m{^text/});
166 $::lxdebug->message(LXDebug->DEBUG2(), "mail6 mtype=" . $attributes{content_type} . " filename=" . $attributes{filename});
169 if ( $attributes{content_type} eq 'message/rfc822' ) {
170 $ent = Email::MIME->new($attachment_content);
171 $ent->header_str_set('Content-disposition' => 'attachment; filename='.$attributes{filename});
173 $ent = Email::MIME->create(
174 attributes => \%attributes,
175 body => $attachment_content,
179 push @{ $self->{mail_attachments}} , SL::DB::EmailJournalAttachment->new(
180 name => $attributes{filename},
181 mime_type => $attributes{content_type},
182 content => ( $email_journal > 1 ? $attachment_content : ' '),
189 sub _create_message {
194 push @{ $self->{headers} }, (Type => "multipart/mixed");
196 if ($self->{message}) {
197 push @parts, Email::MIME->create(
199 content_type => $self->{contenttype},
200 charset => $self->{charset},
201 encoding => 'quoted-printable',
203 body_str => $self->{message},
206 push @{ $self->{headers} }, (
207 'Content-Type' => qq|$self->{contenttype}; charset="$self->{charset}"|,
211 push @parts, grep { $_ } map { $self->_create_attachment_part($_) } @{ $self->{attachments} || [] };
213 return Email::MIME->create(
214 header_str => $self->{headers},
222 # Create driver for delivery method (sendmail/SMTP)
223 $self->{driver} = eval { $self->_create_driver };
224 if (!$self->{driver}) {
226 $self->_store_in_journal('failed', 'driver could not be created; check your configuration & log files');
227 $::lxdebug->message(LXDebug::WARN(), "Mailer error during 'send': $error");
232 # Set defaults & headers
233 $self->{charset} = 'UTF-8';
234 $self->{contenttype} ||= "text/plain";
236 Subject => $self->{subject},
237 'Message-ID' => '<' . $self->_create_message_id . '>',
238 'X-Mailer' => "kivitendo " . SL::Version->get_version,
240 $self->{mail_attachments} = [];
241 $self->{content_by_name} = $::instance_conf->get_email_journal == 1 && $::instance_conf->get_doc_files;
245 # Clean up To/Cc/Bcc address fields
246 $self->_cleanup_addresses;
247 $self->_create_address_headers;
249 my $email = $self->_create_message;
251 #$::lxdebug->message(0, "message: " . $email->as_string);
254 $::lxdebug->message(LXDebug->DEBUG2(), "mail1 from=".$self->{from}." to=".$self->{to});
255 my $from_obj = (Email::Address->parse($self->{from}))[0];
257 $self->{driver}->start_mail(from => $from_obj->address, to => [ $self->_all_recipients ]);
258 $self->{driver}->print($email->as_string);
259 $self->{driver}->send;
266 $self->{journalentry} = $self->_store_in_journal;
268 return $ok ? '' : ($error || "undefined error");
271 sub _all_recipients {
273 $self->{addresses} ||= {};
274 return map { @{ $self->{addresses}->{$_} || [] } } qw(to cc bcc);
277 sub _store_in_journal {
278 my ($self, $status, $extended_status) = @_;
280 my $journal_enable = $::instance_conf->get_email_journal;
282 return if $journal_enable == 0;
284 $status //= $self->{driver}->status if $self->{driver};
285 $status //= 'failed';
286 $extended_status //= $self->{driver}->extended_status if $self->{driver};
287 $extended_status //= 'unknown error';
289 my $headers = join "\r\n", (bundle_by { join(': ', @_) } 2, @{ $self->{headers} || [] });
291 my $jentry = SL::DB::EmailJournal->new(
292 sender => SL::DB::Manager::Employee->current,
293 from => $self->{from} // '',
294 recipients => join(', ', $self->_all_recipients),
295 subject => $self->{subject} // '',
297 body => $self->{message} // '',
298 sent_on => DateTime->now_local,
299 attachments => \@{ $self->{mail_attachments} },
301 extended_status => $extended_status,