#!/usr/bin/perl
#######################################################
# sendEmail
# Written by: Brandon Zehm <caspian@linuxfreak.com>
#
# License:
# This software may be freely distributed, used, and
# modified, provided that this disclaimer and my name
# are included in the code.
#
# Disclaimer:
# -- insert standard disclaimer here ;) --
# I am not responsible for anything you do with this
# software, or anything that happens from the use of
# this software, including but not limited to anything
# you, your lawyers, or anyone else can think of.
#
#######################################################
use Socket;

### Global Variables ###

$version = "v1.00";
$from    = '';
$to      = '';
$message = '';
$server  = 'localhost';                          # Defualt server
$port    = '25';                                 # Defualt port
$subject = 'A message delivered by sendEmail';   # Default subject


### Intercept signals and exit cleanly ###

$SIG{'QUIT'} = \&exit;
$SIG{'INT'} = \&exit;
$SIG{'KILL'} = \&exit;
$SIG{'TERM'} = \&exit;


# Setup terminal mode..
  select(STDOUT);
  $| = 1;

# Goto help if there are not at least 3 incoming variables.
if (!$ARGV[2]) { &help; }

# Get incoming variables and assign them into variables..
$numargv = @ARGV;
for ($counter = 0; $counter < $numargv; $counter++) {
  if ($ARGV[$counter] =~ /-s/) {
    $counter++;
    $server = $ARGV[$counter];
  }
  elsif ($ARGV[$counter] =~ /-p/) {
    $counter++;
    $port = $ARGV[$counter];
  }
  elsif ($ARGV[$counter] =~ /-f/) {
    $counter++;
    $from = $ARGV[$counter];
  }
  elsif ($ARGV[$counter] =~ /-t/) {
    $counter++;
    $to = $ARGV[$counter];
  }
  elsif ($ARGV[$counter] =~ /-m/) {
    $counter++;
    $message = $ARGV[$counter];
  }
  elsif ($ARGV[$counter] =~ /-u/) {
    $counter++;
    $subject = $ARGV[$counter];
  }
  else {
    &help;
  }
}

# Check to see that all required variables are filled, or print the help.
if ($from eq '') {
  print "You must specify a \'from\' field.\n\n";
  &help;
}
if ($to eq '') {
  print "You must specify a \'to\' field.\n\n";
  &help;
}
if ($message eq '') {
  print "You must specify a message to send!\n\n";
  &help;
}
if ($server eq '') {
  $server = 'localhost';
}
if ($port eq '') {
  $port = 25;
}

# Connect, and send the email!
&connect or &exit("\nError Connecting to [$server]!\n");
print SERVER "HELO $server\015\012";
&wait_until_ok or &exit("EXITING\n"); 
print SERVER "MAIL FROM: <$from>\015\012";
&wait_until_ok or &exit("EXITING\n"); 
print SERVER "RCPT TO: <$to>\015\012";
&wait_until_ok or &exit("EXITING\n"); 
print SERVER "DATA\015\012";
&wait_until_ok or &exit("EXITING\n"); 
print SERVER "From: $from\015\012To: $to\015\012Subject: $subject\015\012X-Mailer: sendEmail $version\015\012";
print SERVER "\015\012$message\015\012\015\012.\015\012";
# We are done!!!
&close_server;
&exit("Email was sent successfully!\n");


#########################################################
# SUB: help
#
# For all those dumb newbies ;)
#########################################################
sub help {
print <<EOM;

sendEmail $version
Written by: Brandon Zehm <caspian\@linuxfreak.com>

Usage:  sendEmail [options]
        
        -f <from>
        -t <to>
        -m <message>
        -u <subject>       (Optional, there is a default subject)
        -s <email server>  (Optional, default is localhost)
        -p <port>          (Optional, default is 25)

EOM
exit;
}



#########################################################
# SUB: &connect
# Returns 1 on success 0 on failure.
#########################################################
sub connect {
  ### Open a IP socket in stream mode wiht tcp protocol. 
  socket(SERVER, PF_INET, SOCK_STREAM, getprotobyname('tcp')) || return(0);

  ### Create the data structure $dest by calling sockaddr_in(port, 32bit IP)
  my $dest = sockaddr_in ($port, inet_aton($server)) || return(0);

  ### Connect our socket to SERVER
  connect(SERVER, $dest) || return(0);

  ### Force our output to flush immediatly after a print.
  select(SERVER);
  $| = 1;
  select(STDOUT);

  ### We should be connected now.
#    print "Connected successfully..\n";

  return(1);
}




#########################################################
# SUB: &close_server
# Closes the SERVER socket.
# Returns 1 on success 0 on failure.
#########################################################
sub close_server {
  print SERVER "QUIT\015\012";
  sleep(1);
  if (!(close SERVER)) {
    return(0);
  }
  return(1);
}



#########################################################
# SUB: &wait_until_ok
# Reads lines form the server until a line contains 
# a 'OK'
# Returns 1 on success or 0 if and error message is 
# received from the server.
#########################################################
sub wait_until_ok {
  my $string = '';
  until ($string =~ m/211|220|221|250|354/g) {  # A positive POP3 response
    $string = <SERVER>;
#    print "Server: ", $string; 
    if ($string =~ m/500|501|502|503|504|214|421|450|550|451|551|452|552|553|554/g) {  # A negative POP3 response
      print "\nThe server returned the folling error:\n$string\n";
      return(0);
    }
  }
  return(1);
}


sub exit {
  print @_[0];
  exit;
}