#!/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.22";
$from    = '';
@to      = ();
$message = '';
$server  = 'localhost';                          # Defualt server
$port    = '25';                                 # Defualt port
$subject = '';                                   # Default subject
$logging = 0;                                    # Disable logging by default
$logfile = '/var/log/messages';                  # Default file for logging
$debug   = 0;                                    # Default verbosity level




################################
#  required startup jibberish  #
################################

### Intercept signals and exit cleanly ###
$SIG{'QUIT'} = \&exit;
$SIG{'INT'} = \&exit;
$SIG{'KILL'} = \&exit;
$SIG{'TERM'} = \&exit;
$SIG{'HUP'} = \&exit;

### Abort program after 15 seconds ###
alarm(15);

### Set terminal to non-buffering mode ###
select(STDOUT);
$| = 1;

### Display help if no command line options are present ###
if (!$ARGV[0]) { &help; }





##########################
#  Process command line  #
##########################

$numargv = @ARGV;
for ($counter = 0; $counter < $numargv; $counter++) {
  if ($ARGV[$counter] =~ /^-f/) {                  ### From ###
    $counter++;
    if ($ARGV[$counter] && $ARGV[$counter] !~ /^-/) {
      $from = $ARGV[$counter];
    }
  }
  elsif ($ARGV[$counter] =~ /^-t/) {               ### To ###
    $counter++;
    while ($ARGV[$counter] && ($ARGV[$counter] !~ /^-/)) {
      push (@to,$ARGV[$counter]);
      $counter++;
    } $counter--;
  }
  elsif ($ARGV[$counter] =~ /^-m/) {               ### Message ###
    $counter++;
    if ($ARGV[$counter] && $ARGV[$counter] !~ /^-/) {
      $message = $ARGV[$counter];
    }
  }
  elsif ($ARGV[$counter] =~ /^-u/) {               ### Subject ###
    $counter++;
    if ($ARGV[$counter] && $ARGV[$counter] !~ /^-/) {
      $subject = $ARGV[$counter];
    }
  }
  elsif ($ARGV[$counter] =~ /^-s/) {               ### Server ###
    $counter++;
    if ($ARGV[$counter] && $ARGV[$counter] !~ /^-/) {
      $server = $ARGV[$counter];
    }
  }
  elsif ($ARGV[$counter] =~ /^-l/) {               ### Logging ###
    $counter++;
    $logging = 1;
    if ($ARGV[$counter] && $ARGV[$counter] !~ /^-/) {
      $logfile = $ARGV[$counter];
    }
  }
  elsif ($ARGV[$counter] =~ /^-p/) {               ### Port ###
    $counter++;
    if ($ARGV[$counter] && $ARGV[$counter] !~ /^-/) {
      $port = $ARGV[$counter];
    }
  }
  elsif ($ARGV[$counter] =~ /^-v/) {               ### Verbosity ###
    if ($ARGV[$counter] eq "-v") {
      $debug = 1 if ($debug <= 1);
    }
    elsif ($ARGV[$counter] eq "-vv") {
      $debug = 6 if ($debug <= 6);
    }
  }
  else {                                           ### Help ###
    &exit("ERROR:  The option '$ARGV[$counter]' is unrecognised.\n");
  }
}





#################################################
#  Verify required variables are set correctly  #
#################################################

if ($from eq '') {
  print "You must specify a 'from' field.\n\n";
  &help;
}
if ($to[0] eq '') {
  print "You must specify a 'to' field.\n\n";
  &help;
}
if ($server eq '') {
  $server = 'localhost';
}
if ($port eq '') {
  $port = 25;
}



#################################################
#  Read $message from STDIN if -m was not used  #
#################################################

if (!($message)) {
  alarm(60);
  print "Reading message from STDIN because no '-m' option was used.\n";
  print "If you are manually typing in a message:\n"; 
  print "  - Program will abort if a new line is not received once every 60 seconds.\n";
  print "  - End manual input with a CTRL-D on its own line.\n\n";
  while (<STDIN>) {               # Read STDIN into $message
    $message = $message . $_;
    alarm(60);
  }
  $message =~ s/\012/\015\012/g;  # Fix lines eith bare LF's
}




#################################
#  Connect, and send the email  #
#################################

print "Connecting to: $server:$port\n" if ($debug > 0);
&connect or &exit();
&read_server_response or &exit("EXITING\n"); 

print "Sending mail commands: \n" if ($debug > 0);

print "\tHELO -> " if ($debug > 0);
print SERVER "HELO $server\015\012";
&read_server_response or &exit("EXITING\n"); 
print "OK\n" if ($debug == 1);

print "\tMAIL FROM -> " if ($debug > 0);
print SERVER "MAIL FROM: <$from>\015\012";
&read_server_response or &exit("EXITING\n"); 
print "OK\n" if ($debug == 1);

print "\tRCTP TO -> " if ($debug > 0);
for ($a = 0; $a < scalar(@to); $a++) {
  print SERVER "RCPT TO: <$to[$a]>\015\012";
  &read_server_response or &exit("EXITING\n"); 
}
print "OK\n" if ($debug == 1);

print "\tDATA -> " if ($debug > 0);
print SERVER "DATA\015\012";
&read_server_response 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";
&read_server_response or &exit("EXITING\n");
print "OK\n" if ($debug == 1);



####################
#  We are done!!!  #
####################

print "Disconnecting.\n" if ($debug > 0);
&close_server;




#####################################
#  Log to a file if -l is specified #
#####################################

if ($logging) {
  print "Logging this transaction to: $logfile\n" if ($debug > 0);
  print "Opening file: " if ($debug > 5);
  if (!(open(LOG, ">> $logfile"))) {
    print "failure\n" if ($debug > 5);
    print "WARNING -- Error opening the file: [$logfile]\n";
  }
  else {
    print "success\n" if ($debug > 5);
    
    # Get the date
    print "Getting the date\n" if ($debug > 5);
    my $date = time();
    ($sec,$min,$hour,$mday,$mon,$null,$null,$null,$null) = localtime($date);
    $mon = return_month($mon);
    $date = "$mon $mday $hour:$min:$sec";
    
    # Get HOSTNAME
    print "Getting the hostname\n" if ($debug > 5);
    my $hostname = $ENV{'HOSTNAME'};
    $hostname =~ s/\..*$//;
    
    # Write the LOG entry
    print "Writing the log entry\n" if ($debug > 5);
    print LOG "$date $hostname sendEmail\[$$\]: Email sent successfully.  To: ";
    for ($a = 0; $a < scalar(@to); $a++) {
      print LOG "[$to[$a]] ";
    }
    print LOG "Subject: [$subject]\n";
    print "Closing log file\n" if ($debug > 5);
		close(LOG);
  }
}



######################
#  Exit the program  #
######################

print "Exiting the program\n" if ($debug > 5);
&exit("Email was sent successfully!\n");









#########################################################
# SUB: help
#
# hehe, for all those newbies ;)
#########################################################
sub help {
print <<EOM;

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

Usage:  sendEmail [options]   or   cat file | sendEmail [options]

  Required:
    -f <from>
    -t <to> ... ...    Multiple addresses allowed
  
  Optional:
    -m <message>       If -m is absent, message is read from STDIN
    -u <subject>       
    -s <email server>  default is localhost
    -l <logfile>       if -l is absent nothing will be logged
    -p <port>          default is 25
    -v                 verbose output
    -vv                very verbose output

EOM
exit;
}



#########################################################
# SUB: &connect
# Returns 1 on success 0 on failure.
#########################################################
sub connect {
  print "connect() - sub entry\n" if ($debug > 5);
  my $return = 1;
  
  ### Open a IP socket in stream mode with tcp protocol. 
  print "connect() - requesting a streaming tcp/ip socket from the system\n" if ($debug > 5);
  socket(SERVER, PF_INET, SOCK_STREAM, getprotobyname('tcp')) || ($return = 0);
  print "ERROR:  Problem opening a tcp/ip socket with the system.\n" if ($return == 0);

  ### Create the data structure $dest by calling sockaddr_in(port, 32bit IP)
  print "connect() - creating data structure from server name and port\n" if ($debug > 5);
  my $dest = sockaddr_in ($port, inet_aton($server)) || ($return = 0);
  print "ERROR: Calling sockaddr_in() returned an error\n" if ($return == 0);

  ### Connect our socket to SERVER
  print "connect() - connecting the socket to the server\n" if ($debug > 5);
  connect(SERVER, $dest) || ($return = 0);
  print "ERROR:  Connection attempt to [$server:$port] failed!\nTry specifying another SMTP server with the '-s' option.\n" if ($return == 0);
  print "connect() - successfully connected to $server:$port\n" if (($debug > 5) && ($return));

  ### Force our output to flush immediatly after a print.
  print "connect() - setting non-buffering mode on the network connection\n" if (($debug > 5) && ($return));
  select(SERVER);
  $| = 1;
  select(STDOUT);

  # Return success
  print "connect() - sub exit: returning [$return]\n" if ($debug > 5);
  return($return);
}




#########################################################
# SUB: &close_server
# Closes the SERVER socket.
# Returns 1 on success 0 on failure.
#########################################################
sub close_server {
  print "close_server() - sub entry\n" if ($debug > 5);
  my $return = 1;
  print SERVER "QUIT\015\012";        # Send Quit command
  if (!(close SERVER)) {              # and drop the connection.
    print "ERROR:  There was an error disconnecting form the server\n";
    $return = 0;                      # Return failure if we didn't disconnect correctly
  } 
  print "close_server() - disconnected from the server successfully\n" if ($debug > 5);
  print "close_server() - sub exit: returning [$return]\n" if (($debug > 5) && ($return));
  return($return);                    # Return
}



#########################################################
# SUB: &read_server_response
# Reads lines form the server until a line contains 
# a SMTP response.
#
# Returns 1 on positive SMTP response and 0 on negative
# SMTP response.
#########################################################
sub read_server_response {
  print "\nread_server_response()\n" if ($debug > 5);
  my $return = 0;
  print "  reading a line from the server\n" if ($debug > 5);
  my $string = <SERVER>;                           # Read a line from the remote server
  print "  The server returned:\n  $string" if ($debug > 5);
  if ($string =~ /^211|^220|^221|^250|^354/) {     # A positive SMTP response
    $return = 1;
  }
  elsif ($string =~ /^500|^501|^502|^503|^504|^214|^421|^450|^550|^451|^551|^452|^552|^553|^554/) {  # A negative SMTP response
    print "ERROR:  The server returned the following error:\n$string\n";
    $return = 0;                                   # set return to failure
  }
  print "read_server_response() - returning [$return]\n\n" if ($debug > 5);
  return($return);                                 # Return
}



#########################################################
# SUB: &return_month(0,1,etc)
#  returns the name of the month that corrosponds
#  with the number.  returns 0 on error.
#########################################################
sub return_month {
  my $x = $_[0];
  if ($x == 0)  { return 'Jan'; }
  if ($x == 1)  { return 'Feb'; }
  if ($x == 2)  { return 'Mar'; }
  if ($x == 3)  { return 'Apr'; }
  if ($x == 4)  { return 'May'; }
  if ($x == 5)  { return 'Jun'; }
  if ($x == 6)  { return 'Jul'; }
  if ($x == 7)  { return 'Aug'; }
  if ($x == 8)  { return 'Sep'; }
  if ($x == 9)  { return 'Oct'; }
  if ($x == 10) { return 'Nov'; }
  if ($x == 11) { return 'Dec'; }
  return (0);
}



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

