Sending email using Shell script

By | 23rd August 2020

We often need the email facility in the shell script as most of the batch jobs in production are running in Linux based machines only. In case of issues, the jobs or scheduler needs to send failure notifications to the support DL. At times we may need the failure log as an attachment in the email as well. It is these features that make shell script a very flexible and strong tool in Linux based environments.

Sending an email using mailx

mailx is a utility program that can be installed in Linux based machines for the purpose of sending and receiving emails.

Syntax – Without attachment

echo "Email body" | mailx -s "Email subject" username@domain.com

echo – for appending the content to the email body.

‘|’ – for applying multiple functions one after the other.

mailx – name of the utility

‘-s’ – To add email subject followed by the receiver email ID.

Syntax – With attachment

echo "Email body" | mailx -a "Full_path_of_FilenameWithExtension" -s "Email subject"  username@domain.com

The above statement is the same as the previous one except the ‘-a’ followed by the file to attach

Sending an email using mutt

Similar to mailx, we have another utility that is practiced for sending emails. Although both do the same thing, there is a slight difference in syntax.

Syntax – Without attachment

echo "Email body" | mutt -s "Email subject" -- username@domain.com

echo – for appending the content to the email body.

‘|’ – for applying multiple functions one after the other.

mailx – name of the utility

‘-s’ – To add email subject followed by ‘– receiver email ID’

Syntax – With attachment

echo "Email body" | mutt -a "Full_path_of_FilenameWithExtension" -s "Email subject" -- username@domain.com