Sending Mail to All Users

Sending Mail to All Users

Occasionally, you need to send messages to all users on your system. Warning users of planned downtime for hardware upgrades is a good example. Sending e-mail to each user individually is extremely time consuming and wasteful; this is precisely the kind of task that e-mail aliases and mailing lists were invented for. Keeping a mailing list of all the users on your system can be problematic, however. If you are not diligent about keeping the mailing list current, it becomes increasingly inaccurate as you add and delete users. Also, if your system has many users, the mere size of the alias list can become unwieldy.

The following script, called mailfile, provides a simple method of working around these problems. It grabs the login names from the /etc/passwd file and sends e-mail to all users.

# mailfile: This script mails the specified file to all users
#           of the system.  It skips the first 17 accounts so
#           we do not send the email to system accounts like
#           'root'.
# USAGE: mailfile "Subject goes here" filename.txt
# Check for a subject
if ( `echo $1 | awk '{ print $1 }'` == "" ) then
    echo You did not supply a subject for the message.
    echo Be sure to enclose it in quotes.
    exit 1
    # Get the subject of the message
    set subject=$1
# Check for a filename
if ( $2 == "" ) then
    echo You did not supply a file name.
    exit 2
    # Get the name of the file to send
    set filename=$2
# Check that the file exists
if ( -f $filename ) then
   echo Sending file $filename
   echo File does not exist.
   exit 3
# Loop through every login name, but skip the first 17 accounts
foreach user ( `awk -F: '{ print $1 }' /etc/passwd | tail +17` )
    # Mail the file
    echo Mailing to $user
    mail -s "$subject" $user < $filename
    # sleep for a few seconds so we don't overload the mailer
    # On fast systems or systems with few accounts, you can
    # probably take this delay out.
    sleep 2

The script accepts two parameters. The first is the subject of the e-mail message, which is enclosed in quotes. The second is the name of the file containing the text message to send. Thus, to send an e-mail message to all users warning them about an upcoming server hardware upgrade, I may do something similar to the following:

mailfile "System upgrade at 5:00pm" upgrade.txt

The file upgrade.txt contains the text of the message to be sent to each user. The really useful thing about this approach is that I can save this text file and easily modify and resend it the next time I upgrade the system.


If your users log in to your system using text-based logins instead of graphical logins, you can add messages to the /etc/motd file to have them reach your users. Any text in that file will be displayed on each user's screen after the user logs in and before the first shell prompt appears.

Part IV: Red Hat Linux Network and Server Setup