Mail script output
How-to mail the results of a script
If you have an automated process (running with Cron) for example, you may want to email the output from it to yourself.
Essentially, sending a mail with sendmail is very easy. Create a text file containing the mail and call sendmail with some simple parameters and the file piped into it.
Step 1 – Create The File
The file should consist of three key elements. The subject header (a), the message (b) and the end of file marker (c).
(a) Subject: your subject
(b) Line one of your mail message
Line two of your mail message
So as you can see, this is essentially a very simple process. Using bash we could created something like this.
echo "Subject: Sample mail" > /tmp/mymailfile.txt
echo "Log from automated process" >> /tmp/mymailfile.txt
echo "." >> /tmp/mymailfile.txt
echo >> /tmp/mymailfile.txt
We have just created a mail file suitable for use with sendmail.
Step 2 – Mail The File
Once you have your file, you will want to mail it. Using sendmail for this purpose is essentially very simple. You need to provide a to and a from address using command line parameters and also pipe the file you created earlier into it.
cat /tmp/mymailfile.txt | sendmail -firstname.lastname@example.org email@example.com
And that is essentially that. Providing user access is correct, you should be able to achieve the automated mailing of script results with the minimum of hassle.
A full example
# Start the mail file
echo "Subject: Automated Script Log" > /tmp/myscript.log
# Pipe the results of the script to the mail file
php -q /usr/local/scripts/myscript.php >> /tmp/myscript.log
# Finish the mail file
echo "." >> /tmp/myscript.log
echo >> /tmp/myscript.log
# Mail it
cat /tmp/myscript.log | /usr/sbin/sendmail -firstname.lastname@example.org email@example.com
The -q flag on the call to PHP removes the headers it adds by default to its output. The single > on the first echo has the effect of forcing the overwrite of the file. Subsequent outputs to the file use the double > to append to it. The exact location of sendmail may vary on your system. This is the path used by RedHat 7.1.
Once you’re happy with the script, you can schedule it with Cron and hey presto, automated script that mails the results to you.