#!/usr/bin/perl -w

# Usage: emails06.pl <file.in>  <file.out> 
# 
# Example:  emails06.pl emails06.17Nov05.textmsg emails06.17Nov05.do  emails06.17Nov05.done 40 1000
#
# David Harris, Version of 5 Jan 2007 pm 05:50

# ------------------------------------------------


$debugFlag = 1;
# 0 for $debugFlag sets NO debugging.

# Check the number of arguments on the command line:
if ($#ARGV+1 != 2) {
  die "emails06.pl needs file.in and file.out as arguments";
  };
  
# Check existence of the textfile and email listing file:
(open FILEIN, "<$ARGV[0]") or die "emails06.pl file.in file ($ARGV[0]) not found.\n";
(open FILEOUT, ">$ARGV[1]") or die "emails06.pl email file.out not opened.\n";

# Read in the substitutable lines from the textfile opened above:
while ($lineread = <FILEIN>) {
  chomp($lineread);
  if ($lineread =~ m/\@/) {
    print FILEOUT "$lineread\n";
  } ;
};

close(FILEIN);
close(FILEOUT);
exit;


#........................................................................
$emailnumber = 1;  # Counter of emails sent, for output near end.
 
# Do the rest of this program once for each non-empty line in FILEOUT file,
#  until the count limit is reached:
while ((chomp($email = <FILEOUT>)) && (length($email) > 2)
       && ($emailnumber <= $msgslimit)) {
  # Put fields into array.
  @fields = split /\|/, $email;

  # Now @messagearray has the text with the targets embedded,
  #     @substit has the images of the targets,
  #     @subsfield has the numbers of the fields that are  used, and
  #     @fields has the fields OF THIS PARTICULAR EMAIL FILE LINE
  #        to put in place of the targets.

  # Exception handler starts with eval around the block that might
  # throw an exeption:  [REMOVED!!]
  # Activate the SMTP link: [IMPLEMENTING A RETRY ABILITY]
  $numretries = 0;
  RETRY: for ($retries = $numretries; $retries >= 0; $retries--) {
  # Make the 'Date:' string for this particular email
  ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
                  localtime(time-(0*3600)-3);  # Future time zone correction?
  $weekday = (Sun,Mon,Tue,Wed,Thu,Fri,Sat)[$wday];
  $monthname = (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec)[$mon];
  $yr2000 = $year+1900;
  if (length($mday) == 1) {
    $mday = '0'.$mday;
  }
  if (length($hour) == 1) {
    $hour = '0'.$hour;
  }
  if (length($min) == 1) {
    $min = '0'.$min;
  }
  if (length($sec) == 1) {
    $sec = '0'.$sec;
  }
  $datestr = "$weekday, $mday $monthname $yr2000 $hour\:$min\:$sec +0000\n";
  $hadwarning = 0;  # Set problem flag to "No problemo" before trying to send.
      # $servername comes from smtppwd.txt file here.:
      if ($debugFlag eq '0') {
        $smtp = Net::SMTP->new( Host => $servername,
                                Hello => 'darwinday.sbcglobal.net',
                                Timeout => 120 );
      } else {
        $smtp = Net::SMTP->new( Host => $servername,
                                Hello => 'darwinday.sbcglobal.net',
                                Timeout => 120,
                                Debug => 1 );     # Non-zero says DO debugging.
      }
      sleep 2;  # Does this give enough time to avoid the "auth error"
                #   problems?
      $smtp->auth($smtpusername,$passwd);  # Authentication!
      #Start of substitutable message, as stored in array by code above
      for ($j = 0; $j
           < $msglines; $j++) {  # Step thru array of stored lines
        $linetosend = $messagearray[$j];
        for ($i = 0; $i < $linenum; $i++) {  #For this line, make substitutions
          # Make a substitution as often as needed in 1 line:
          ($linetosend = $linetosend) =~ s/$substit[$i]/$fields[$subsfield[$i]-1]/g;
        }
        # Special calls for the first 3 lines:
        SWITCH: {
          if ($j == 0) { eval'$smtp->mail($linetosend)';
                        if ($@) {warn("WARNING: $@\n"); $hadwarning = 1 };
              last SWITCH;
          }
          if ($j == 1) { eval'$smtp->recipient($linetosend)';
                        if ($@) {warn("WARNING: $@\n"); $hadwarning = 1 };
              last SWITCH;
          }
          # Blank line then the computed date:
          if ($j == 2) { eval'$smtp->data()';
                        if ($@) {warn("WARNING: $@\n"); $hadwarning = 1 };
              last SWITCH;
          }
          # All further lines:

          if ($linetosend =~ m/^From: /) {
            $smtp->datasend("Date: $datestr");  # Emit computed date
          }
          chomp($linetosend);  # Lines must end with CR/LF!
          eval '$smtp->datasend($linetosend."\r\n")';
                if ($@) {warn("WARNING: $@\n"); $hadwarning = 1 };
          #print STDERR "DOLLAR-AT VALUE IS $@\n"; 
        } # End of SWITCH.
      }
      $smtp->dataend();
      $smtp->quit;
      # Write the emails.txt line that was attempted to be sent, and its number:
      chomp($dateinsert = $datestr);
      # Cause ATTEMPTSs log to flush after every char write
      #                (from p.781 of Programming Perl, v.3):
      my $oldfilehandle = select ATTEMPTS; $| = 1 ; select $oldfilehandle;
      if ($hadwarning == 1) {
        print ATTEMPTS  "$dateinsert HADWARNING |$emailnumber|$email\n" ;
        print STDERR "At $dateinsert HADWARNING #$emailnumber: $email\n" ;        
      } else {
        print ATTEMPTS  "$dateinsert processed|$emailnumber|$email\n" ;
        print STDERR "At $dateinsert processed #$emailnumber: $email\n" ;
        $emailnumber++ ;  # Only increment on successes
      }
      # Let some seconds elapse: the specified time plus randomly to 100% more:
      sleep $delayseconds + int(rand ($delayseconds * 100/100)) ;
    } # End of RETRY: FOR loop.
  }  # End of processing one line of email addresses (one person).
print STDERR "ATTEMPTS file closed and about to exit now.\n" ;
exit;