mail Command in Shell Scripting

mail is an intelligent mail processing system which has a command syntax reminiscent of ed with lines replaced by messages.
mail is part of mailutils package in Debian-Based distros and is a very useful and powerful tool which can be used in scripts.

Some basic examples:

mail -s 'Subject' local_username
mail -s 'Subject' recipient@domain.tld
mail -s 'Subject' recipient@domain.tld < /tmp/message_body
mail -s 'Subject' -c recipient1@domain1.tld recipient2@domain2.tld </var/log/test.log
mail -s 'Subject' -c recipient1@domain1.tld -b recipient2@domain2.tld </var/log/test.log

-s ‘free text’: Specify subject.
-c: Send carbon-copies to list of users.
-b: Send blind-carbon-copies to list. (comma-separated list of names).
< /path/file: Read email body from file.

Sending File Attachments
uuencode is needed to send a binary file, attached to the message:

uuencode archive.tar.gz | mail -s "Subject" recipient@domain.tld

or to send (for example) images:

uuencode image1.png image2.jpg | mail -s "Subject" recipient@domain.tld

Sending Messages using Here-Documents to . compose Mail Body
The here-documents (redirection) tells the shell to read input from the current source (HERE) until a line containing only word (HERE) is seen:

mail -s "Subject" recipient@domain.tld<<EOF
This is a demo report for $(hostname)
Interface $(interface_name) is $(interface_status)
Please investigate.

Sending Empty Mail Body
To use an empty line as the mail body it’s possible to use /dev/null or echo command:

mail -s "Subject" recipient@domain.tld </dev/null

Comments are closed.