#! /usr/bin/perl -w

use IO::Handle;
use Getopt::Std;
use Net::SMTP;

sub status
{
    my ($smtp, $msg) = @_;
    #STDERR->print("$msg -> " . $smtp->code . ' ' . $smtp->message());
}


$hostname = `hostname`;
chomp($hostname);

our $opt_H = 'localhost';
our $opt_D = undef;
our $opt_a = undef;
our $opt_m = '';
our $opt_f = undef;
our $opt_t = undef;
our $opt_s = "DEBUG: $hostname test";

getopts('a:Df:H:m:t:s:');

my $msg = '';
if ($opt_m eq '')
{
	while (<>)
	{
		$msg .= $_;
	}
}
else
{
	$msg = $opt_m;
}

@rcpts = split(/,\s*/, $opt_t);

my $failed = 0;
my $smtp = Net::SMTP->new($opt_H, Debug => $opt_D);

if (defined $opt_a)
{
	my ($username, $password) = split(/:/, $opt_a);
	$smtp->auth($username, $password);
	status($smtp, "auth $username");
	if (!$smtp->ok())
	{
		$failed = 1;
	}
}

if (!$failed)
{
	$smtp->mail($opt_f);
	status($smtp, "mail from $opt_f");
	if (!$smtp->ok())
	{
		$failed = 1;
	}
}

if (!$failed)
{
	foreach my $r (@rcpts)
	{
		$smtp->to($r);
		status($smtp, "recipient $r");
		if (!$smtp->ok())
		{
			$failed = 1;
			last;
		}
	}
}

if (!$failed)
{
	$smtp->data();
	if (!$smtp->ok())
	{
		$failed = 1;
	}
}
if (!$failed)
{
	$smtp->datasend(<<EOF);
To: $opt_t
From: $opt_f
Subject: $opt_s

$msg
EOF
	$smtp->dataend();
	status($smtp, "mail data");
}
if ($failed)
{
	$smtp->reset();
}
$smtp->quit();

