Title: Use Mail as a Client
Course: CIS 208: Linux/UNIX III: Intermediate System Administration, Networking, and Security ~ For IGNITE Review > Section: Learning Modules

Use Mail as a Client

The traditional email client for Unix is mail, and a newer version named mailx is now available.  There have been multiple versions of each of these programs, so consult the man page for mail or mailx for specific details on a particular server.

For Red Hat derivative distributions, run "yum install mailx" to install the mail program.

If mail is run without any options, either the user's inbox is displayed or a message shows that there is no mail for the user.

- The inbox is displayed with a number and a subject line identifying each message.
- Type "?" to see a help message that shows commands to read, reply to, delete and manage messages.
- The "q" command will quit updating the status of the inbox, and the "x" command will exit without updating the status of the inbox.

To send email interactively, type mail followed by one or more email addresses.

- The program will prompt you for a subject and then will accept the body of the message.
- Type a ctrl-D or a single dot (.) at the beginning of a line to complete the message.

To send the contents of a file from the command line, use a pipe or a redirection for the source and add a "-s" flag with the subject of the message.  Here are two examples of this usage.

cat /etc/resolv.conf | mail -s "my resolv.conf file" user@sample.com
mail -s "my hosts file" user@sample.com < /etc/hosts

It is often convenient to send email within a script.  In this first example email is sent to a user with the output of the df command.  A script like this can easily be called by a cronjob.

#!/bin/sh
df -h | mail -s "Disk usage report" user@sample.com

A second example shows a more complex report which can be generated and sent by email.

#!/bin/sh

subject="Daily report for 'hostname'."
recipients="user@sample.com user2@sample.com"

message(){
car <<EoT
Today is 'date +%F'.

'df-h'

The following users are currently logged in:
'who | sed 's.*//' | sort | uniq -c'

Eot
}

message | mail -s "$subject" $recipients