How to redirect local root mail to an external email address on Linux

I run a home file, media and backup server at home on Ubuntu Server 12.04 LTS. I have various cron jobs set-up for various task such as backing up external MySQL databases, web site data and other tasks.

By default, when a cron job runs and if the script or program that runs produces any output (text on the screen) this will email the cron user, in my case, I have setup cron jobs under the root user, therefore emails get sent to root@hostname, so everytime I login via. SSH (which is very rare) I get told about X amount of unread email in /var/mail/root. Now obviously for cron jobs that do create output but you don’t care you can append the cron job line to redirect the output (by appending ‘> /dev/null‘) like so:-

0 * * * * python /etc/example.py > /dev/null

However sometimes you want to know if particular tasks have run successfully and to only have to check a single (external) mail account is much more reasonable, so I’m going to show you how to create a mail alias so emails get sent directly to your external email account.

First of all you need to make sure that you have a mail server installed on your server, I have a default install of Postfix installed, I’ve not done any special configuration to it at all, it will simple be used to end emails externally. – My home server is not set-up to receive any external emails etc.

Lets add your email address as an alias…

So with you favioure text editor, lets edit the /etc/aliases file and add your username and external email address like so:-

root: yourexternalemailaddress@gmail.com

Now run this command:-

newaliases

Now restart Postfix:-

service postfix restart

and to test, run the following command:-

echo test | mail -s "test message" root

You should now be able to check your external email account, in this example I’ve used a gmail account! – Login to your external email account and you should then see your email (if its not in your inbox, check your SPAM folder!)

Hope this will help some people looking to do the same 🙂

Update: I recently ran through this tutorial on Ubuntu Server 14.04 LTS and found that in order to use the ‘postmap’ command you had to force permissions on the /etc/postfix directory, so if you receive errors such as ‘postmap: fatal: cannot remove zero-length database file /etc/postfix/sasl_passwd.db: Permission denied.’ execute the following command of which will resolve the permissions errors and should then let you re-run the command successfully!

sudo chown postfix /etc/postfix
 

3 thoughts on “How to redirect local root mail to an external email address on Linux

Comments are closed.