Thursday, February 25, 2010

Forward mail to another MTA (overwriting the php mail() function)

Original Post: May 8th, 2008

This post explains how to forward all the mail for an existing site using an MTA other than the site’s server it self. The usual technique to achieve this is to configure the local MTA to forward all the mail to another server. In this document I apply a different technique that overwrites the mail() function call to the `sendmail` command.

The advantage of this technique is that no extra headers are added to the message envelope. Why it is necessary to avoid adding extra headers differs from business to business.

Note: the technique here only applies to web applications running on *Nix machines. Windows machines running PHP applications can provide host and port in the php.ini or the apache configuration to achieve the same results.
Overwriting the sendmail Call

There is a couple of ways the `sendmail` path can be overwritten. The most common one is the php.ini and the least common one the php_admin_value directive in the apache configuration. We are going focus on the later one since this directive gives us the possibility to change the value for a single site on a machine that runs multiple virtual web accounts.

1. AS root create a directory for your `sendmail` replacement
mkdir -p /usr/local/forwarder

2. Download the SMTP Class.
wget -O /usr/local/forwarder/smtp.class.php

3. Download the sendmail replacement script
wget -O /usr/local/forwarder/mail.php

4. Open the mail.php file on your favorite editor and change the $HOST, $default_from and
$default_return_path variables to suit your needs.

$HOST = ''; //mx server to forward to
$default_from = '"Web Master" '; //default from line
$default_return_path = ''; // address to deliver the bounces to

5. Open your Apache virtual host configuration file for your domain and put the following line some where in the <VirtualHost>...</VirtualHost> tags

php_admin_value sendmail_path /usr/local/bin/forwarder/

6. Restart you Apache server.



  1. This is a nice article..
    Its easy to understand ..
    And this article is using to learn something about it..

    c#,, php tutorial, Ms sql server

    Thanks a lot..!

  2. This comment has been removed by the author.

  3. Nice article,
    but the script doesn't exists anymore...

  4. Hello!

    This is what I really really need. Do you still have those files somewhere? I would really appreciate you posting them!