I got the SMTP part to work with the code below.
Corion said to use binmode with \r\n, but I'm not sure if Socket is doing it. Because it seems to work with and without binmode now.
Update: FYI: The code below needs you to have a tab \t in the start of the message for it to work.
sub send_email {
my ($self, %email_set) = @_;
# Format input.
$email_set{to} =~ s/[ \t]+/, /g;
$email_set{from} =~ s/.*<([^\s]*?)>/$1/;
$email_set{message} =~ s/^\./\.\./gm;
$email_set{message} =~ s/\r\n/\n/g;
$email_set{message} =~ s/\n/\r\n/g;
$cfg{smtp_server} =~ s/\A\s+|\s+\z//g;
# Send email via SMTP.
if ($cfg{mail_type} == 1) {
use Carp;
use Socket;
my $proto = getprotobyname('tcp') || 6;
my $port = getservbyname('SMTP', 'tcp') || 25;
my $remoteserver = inet_aton($cfg{smtp_server})
or croak 'Unable to resolve hostname : '.$cfg{smtp_server};
croak 'Socket failure. '.$! if (! socket(S, AF_INET, SOCK_STREAM, $p
+roto));
croak 'Bind failure. '.$! if (! bind(S, sockaddr_in(0, INADDR_ANY)))
+;
croak 'Connection to '.$cfg{smtp_server}.' has failed. '.$!
if (! connect(S, sockaddr_in($port, $remoteserver)));
my $oldfh = select(S);
$| = 1;
select($oldfh);
$_ = <S>;
croak "Sending Email: data in Connect error - 220. $_ $!"
if ($_ !~ /^220/);
print S "HELO $cfg{smtp_server}\r\n";
$_ = <S>;
croak "Sending Email: data in Connect error - 250. $_ $!"
if ($_ !~ /^250/);
print S "MAIL FROM:<$email_set{from}>\r\n";
$_ = <S>;
croak "Sending Email: Sender address '$email_set{from}' not valid. $
+_ $!"
if ($_ !~ /^250/);
print S "RCPT TO: <$email_set{to}>\r\n";
$_ = <S>;
croak "Sending Email: Recipient address '$email_set{to}' not valid.
+$_ $!"
if ($_ !~ /^250/);
print S "DATA\r\n";
$_ = <S>;
croak "Sending Email: Message send failed - 354. $_ $!"
if ($_ !~ /^354/);
}
# Send email via sendmail.
$ENV{PATH} = '';
if ($cfg{mail_type} == 0) {
open S, '| '.$cfg{mail_program}.' -t' or croak 'Mailprogram error. a
+t '.$!;
}
print S "To: $email_set{to}\r\n";
print S "From: $email_set{from}\r\n";
print S "Subject: $email_set{subject}\r\n";
print S "$email_set{message}";
print S "\r\n.\r\n";
# Send email via SMTP.
if ($cfg{mail_type} == 1) {
$_ = <S>;
croak "Sending Email: Message send failed - try again - 250. $_ $!"
if ($_ !~ /^250/);
print S "QUIT\r\n";
}
close(S);
return 1;
}