package TheSMTP;
use strict;
use Net::SMTP;
1;

sub new {
    my $class = shift;
    my($host, $from, $to) = @_;
    my $handle;
    eval {
        local $SIG{ALRM} = sub { die "timed out while getting SMTP handle to '$host'" };
        local $^W = 0; # mute warnings in Net::SMTP
        $handle = Net::SMTP->new($host, 'Timeout' => 15);
        local $SIG{ALRM} = sub { die "timed out while talking with SMTP host '$host'" };
        $handle->mail($from) or die "failed to start sending e-mail from '$from' through '$host'";
        $handle->to($to) or die "failed to send message to '$to' through '$host'";
        $handle->data() or die "failed to start sending e-mail body to '$host'";
    };
    alarm(0); # reset any timeouts
    die if $@; # propagate errors if any
    
    return bless {
        'handle' => $handle,
    }, $class;
}

sub print {
    my $self = shift;
    local $" = '';
    eval {
        local $SIG{ALRM} = sub { die 'timed out while sending e-mail body' };
        local $^W = 0; # mute warnings in Net::SMTP
        $self->{handle}->datasend("@_") or die 'failed to send e-mail body';
    };
    alarm(0); # reset any timeouts
    die if $@; # propagate errors if any
}

sub DESTROY {
    my $self = shift;
    if (defined $self->{handle}) {
        $self->{handle}->dataend();
        $self->{handle}->quit();
    }
}
