How-to: Execute any linux script using mail

The following guide will show you how to execute a php or any other command line program by sending mail to a specific mail address.

This can be used for many applications. For example say that we want to create a new trouble ticket to our organisation's central ticket/issue management system.

The first step is to create and test the script.
<?php
/*
 * newticket.php
 */
error_reporting(E_ALL);

$user="root";
$password="XXX";
$database="tests";

echo "Connecting...\n";

mysql_connect("localhost",$user,$password);
mysql_select_db($database) or die( "Unable to select database");
$dt = date("F j, Y, g:i a s");
$query="insert ticket (description) values (\"$dt\")";
mysql_query($query) or die(mysql_error());
mysql_close();
?>

This scripts assumes that you have the table ticket created in a mysql database called tests:
CREATE TABLE IF NOT EXISTS `ticket` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
)

If you place it for example in /var/www then you can test the php script from the command line using:
php -q /var/www/newticket.php

If everything is OK, this script will insert one row in table ticket with its field description set as the current datetime.

Now, if you don't already have one, you need to install a mail server. In this example I used postfix. So for debian/ubuntu just type:
sudo aptitude install postfix

Postfix doesn't allow by default mail aliases to execute commands. In order to enable this you have to configure postfix for this by adding the following lines of the file main.cf which is located at /etc/postfix. Edit the file with:
sudo vi /etc/postfix/main.cf

And then add the attributes allow_mail_to_commands and allow_mail_to_files:
allow_mail_to_commands = alias,forward,include
allow_mail_to_files = alias,forward,include

Then we need to edit the /etc/aliases in order to add the mail alias that will execute the script we just created:

# See man 5 aliases for format
postmaster:    root
newticket: "| php -q /var/www/newticket.php" 

Now we have to refresh the aliases used by sendmail by executing the command (rebuilds the data base for the mail aliases file.
sudo newaliases

Finally test the alias just created by running the sendmail like this:
user@host:/var/www$ sendmail newticket
.

Don't forget the "." which marks the end of the message body and tells sendmail to actually send the mail.
Now check your database. If everything went fine, you should have a new row inserted in your ticket table.
If not, then you have to do some troubleshooting by running the mailq program to check your mail queue.

2 comments:

  1. in this scenario the mail alias is local only or I can send emails from outside the server?

    ReplyDelete