38ad2b75311b5172ec9d596be871bf1d002974b2
[kivitendo-erp.git] / SL / Mailer / SMTP.pm
1 package SL::Mailer::SMTP;
2
3 use strict;
4
5 use parent qw(Rose::Object);
6
7 use Rose::Object::MakeMethods::Generic
8 (
9   scalar => [ qw(myconfig mailer form) ]
10 );
11
12 my %security_config = (
13   none => { require_module => 'Net::SMTP',          package => 'Net::SMTP',      port =>  25 },
14   tls  => { require_module => 'Net::SSLGlue::SMTP', package => 'Net::SMTP',      port =>  25 },
15   ssl  => { require_module => 'Net::SMTP::SSL',     package => 'Net::SMTP::SSL', port => 465 },
16 );
17
18 sub init {
19   my ($self) = @_;
20
21   Rose::Object::init(@_);
22
23   my $cfg           = $::lx_office_conf{mail_delivery} || {};
24   $self->{security} = exists $security_config{lc $cfg->{security}} ? lc $cfg->{security} : 'none';
25   my $sec_cfg       = $security_config{ $self->{security} };
26
27   eval "require $sec_cfg->{require_module}" or die "$@";
28
29   $self->{smtp} = $sec_cfg->{package}->new($cfg->{host} || 'localhost', Port => $cfg->{port} || $sec_cfg->{port});
30   die unless $self->{smtp};
31
32   $self->{smtp}->starttls(SSL_verify_mode => 0) || die if $self->{security} eq 'tls';
33
34   # Backwards compatibility: older Versions used 'user' instead of the
35   # intended 'login'. Support both.
36   my $login = $cfg->{login} || $cfg->{user};
37
38   return 1 unless $login;
39
40   $self->{smtp}->auth($login, $cfg->{password}) or die;
41 }
42
43 sub start_mail {
44   my ($self, %params) = @_;
45
46   $self->{smtp}->mail($params{from});
47   $self->{smtp}->recipient(@{ $params{to} });
48   $self->{smtp}->data;
49 }
50
51 sub print {
52   my $self = shift;
53
54   # SMTP requires at most 1000 characters per line. Each line must be
55   # terminated with <CRLF>, meaning \r\n in Perl.
56
57   # First, normalize the string by removing all \r in order to fix
58   # possible wrong combinations like \n\r.
59   my $str = join '', @_;
60   $str    =~ s/\r//g;
61
62   # Now remove the very last newline so that we don't create a
63   # superfluous empty line at the very end.
64   $str =~ s/\n$//;
65
66   # Split the string on newlines keeping trailing empty parts. This is
67   # requires so that input like "Content-Disposition: ..... \n\n" is
68   # treated correctly. That's also why we had to remove the very last
69   # \n in the prior step.
70   my @lines = split /\n/, $str, -1;
71
72   # Send each line terminating it with \r\n.
73   $self->{smtp}->datasend("$_\r\n") for @lines;
74 }
75
76 sub send {
77   my ($self) = @_;
78
79   $self->{smtp}->dataend;
80   $self->{smtp}->quit;
81   delete $self->{smtp};
82 }
83
84 sub keep_from_header {
85   my ($self, $item) = @_;
86   return lc($item) eq 'bcc';
87 }
88
89 1;