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).
For example…
(a) Subject: your subject
(b) Line one of your mail message
Line two of your mail message
(c) .

So as you can see, this is essentially a very simple process. Using bash we could created something like this.

#! /bin/bash
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 -ffrom@address.com to@address.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

#! /bin/bash
# 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 -ffrom@address.com to@address.com

Other Info

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.

You can skip to the end and leave a response. Pinging is currently not allowed.

Leave a Reply


Bad Behavior has blocked 153 access attempts in the last 7 days.