#!/usr/bin/perl
#
# Author:  Petter Reinholdtsen
# Date:    2005-06-06
# License: GNU Public License v2
#
# Script to send a lot of mails from NUUG
#
# Based on script Mass Mailer v1.1 by ickerne (C) 1998

#use warnings;
use strict;

my $debug = 0;

my $sendmail="/usr/sbin/sendmail";
my $sum=0;

if (2 != scalar @ARGV && 3 != scalar @ARGV) {
   print "Usage: $0 <template> <addressfile> [<envelope-from>]\n";
   print "  The template should be a complete mail, including headers,\n";
   print "  where <TO> will be replaced with the receivers address.\n";
   exit 1;
}

my $templatefile=$ARGV[0];
my $addressfile=$ARGV[1];
my $envelopefrom=$ARGV[2];

sub send_mail {
    my $text = shift;
    if ($debug) {
        print "============\n";
        print "$text\n";
        print "============\n";
    } else {
        if ($envelopefrom) {
            open(SENDMAIL, "|$sendmail -t -f $envelopefrom") or die "Unable to run $sendmail";
        } else {
            open(SENDMAIL, "|$sendmail -t") or die "Unable to run $sendmail";
        }
        print SENDMAIL $text;
        close(SENDMAIL);
    }
}

sub get_template {
    my $templatefile = shift;
    open(TEMPLATE, "<", $templatefile) or die "Unable to read from $templatefile";
    my @lines = <TEMPLATE>;
    return join("", @lines);
}

sub update_template {
    my ($text, %map) = @_;
    for my $key (keys %map) {
        $text =~ s/$key/$map{$key}/g;
    }
    return $text;
}

my $template = get_template($templatefile);

open(ADDR, "<", $addressfile) or die "Unable to read from $addressfile";
while (<ADDR>) {
    chomp;
    s/#.*$//;
    next if (m/^\s*$/);
    my $address = $_;
    $sum++;
    my $text = update_template($template, ('<TO>' => $address) );
    send_mail($text);
}
print "$sum mail(s) sent.\n"
