:
##########################################################################
# Title      :	maillist - send mail to multiple recipients
# Author     :	Heiner Steven <heiner.steven@odn.de>
# Date       :	1999-09-05
# Requires   :	getopts, MAILX
# Category   :	Mail
# SCCS-Id.   :	@(#) maillist	1.5 04/07/27
##########################################################################
# Description
#
# Notes
#	At this time there must be a list file. This should
#	not be necessary.
##########################################################################

PN=`basename "$0"`
VER='1.5'

# Determine mail program allowing to set subject with "-s".
# The last program is the default value.
for Mailer in /bin/mailx /usr/ucb/mail /bin/Mail /usr/ucb/Mail mail
do
    [ -x "$Mailer" ] && break
done

SleepTime=2			# Wait this time for the mailer to complete

Msg () {
    echo >&2 "$PN:" "$@"
}

Fatal () {
    Msg "$@"
    exit 1
}

Usage () {
    echo >&2 "$PN - send mail to multiple recipients, $VER
usage: $PN [-vF] [-b batchsize] [-f listfile] [-s Subject] mailfile

Mailfile contains the mail to be send.  Listfile contains
a list of recipients, one e-mail address per line. If no
listfile is given, the addresses are read from standard input."
    exit 0
}

BatchSize=10
List=
Subject=
force=no
verbose=no
while getopts b:hFf:s:v Opt
do
    case "$Opt" in
        b)	BatchSize=$OPTARG;;
	f)	List=$OPTARG;;
	F)	force=yes;;
	s)	Subject=$OPTARG;;
	v)	verbose=yes;;
	?)	Usage;;
    esac
done
shift `expr $OPTIND - 1`

[ $# -eq 1 ] || Usage

MailFile="$1"
[ -r "$MailFile" ] || Fatal "cannot read mail file $MailFile"
[ -n "$List" -a -r "$List" ] || Fatal "cannot read list file $List"

# Convert DOS mail file to UNIX format
set -e				# Abort at first error
sed 's:$::' "$MailFile" > ml$$
mv ml$$ "$MailFile"
set +e

MailCnt=`wc -l < "$List"`
MailCnt=`echo ${MailCnt:-0}`

if [ -n "$List" -a $force = no ]
then
    echo >&2 "Do you really want to send $MailCnt emails (y/n)? \c"
    read ok || exit 2
    case "$ok" in
	[yYjJ]*)    ;;
	*)	Fatal "no mail sent";;
    esac
fi

[ $verbose = yes ] &&
	Msg "Estimated time for sending the messages: \
`expr \( \( $MailCnt / $BatchSize \* $SleepTime \) + 1 \) / 60 ` minutes"

if [ -n "$Subject" ]
then
    MailFlags="-s \"$Subject\""
fi

cnt=0
sed 's:$::' $List |		# Convert DOS text files to unix format
    sort -u |			# Process each address only once
    while read Address
    do
	if [ $cnt -ge $BatchSize ]
	then
	    if [ $verbose = yes ]
	    then
		i=`expr ${i:-0} + 1`
		echo "processing #`expr $BatchSize \* $i` of $MailCnt mails...\r\c"
	    fi
	    cnt=0
	    sleep $SleepTime
	fi
	cnt=`expr $cnt + 1`
	eval "$Mailer $MailFlags $Address < $MailFile"
    done

Msg "all mails sent."
exit 0
