Mail trick: How to fetch your mail only when there is mail

Translation of the original in Catalan. Read it in: CatalàCastellano

This 'trick' is only useful for a few, but I just want to put on record that sometimes you can do 'little inventions' in order to customise our way of working with mail. What has to be true for this to be useful for you:

  1. You can manage your mail server, or you're 'friends' with the administrator.

  2. You have a web server where you'll fetch your mail

  3. Your address from where you fetch your mail is routable at all times.

Goal: not to run 'fetchmail' periodically but only when the mail server has mail.

The concept is very simple it's about setting up a daemon/crontask that watches whether there is mail in our server account, for example:

root@s0-ret:~/scripts# cat mailNotify.sh

MBOX="/var/spool/vmail/SERVERS/joor.net/oriol

/var/spool/vmail/SERVERS/inforcomsoft.net/orius

/var/spool/vmail/SERVERS/joor.net/oriol-ml"

for BOX in $MBOX

do

if [ -s $BOX ]

then

lynx -dump http://oriol.joor.net/CorreuNou.php > /dev/null 2>&1

fi

done
*

as you can see in the script when it finds that in one of the mbox files of the pop3 accounts there is mail it launches an HTTP request against a file CorreuNou.php:

<?

system('echo > /var/spool/internet/newMail');

system('chmod 660 /var/spool/internet/newMail');

?>
*

the /var/spool/internet directory is owned by apache and also belongs to this group. As you can see the .php file is as simple as creating a file inside this directory and we give it read and write permissions for apache:apache.

On the local server, besides the php file, we also have a daemon/crontask that watches whether this file is created, this task is launched by the user who wants to fetch the mail and it's made to belong to the group apache so that it can delete this notification file. The routine in question could be like this:

NOTIFY="/var/spool/internet/newMail"

if [ -e $NOTIFY ]

then

cd

fetchmail > /dev/null 2>&1

rm $NOTIFY

fi
*

With this silly little thing we no longer need to launch 'fetchmail' every so often so that it fetches our mail. Instead it will be launched every time the server tells it there is mail. The mail won't arrive in real time, but almost almost... so I think it's a more than sufficient solution for me.

The advantages I get with this:

  1. I don't have to redirect the POP3 accounts that belong to domains that aren't mine.

  2. I can keep my SMTP port well closed to the outside.

  3. For many purposes, it's as if I had the SMTP port open.

Let's see if during these days I write the HOWTO of the mail system I set up for myself a few weeks ago. Because by the looks of it I already have it quite refined.