Sandboxing outgoing email

John Morahan's picture

While you're testing email functionality on a website, you don't want to accidentally send out mails to all your (or your clients') end users! There are a few ways to prevent this. Here's the simplest one I've found so far. It allows you to redirect all outgoing email from PHP to a local user (you, for example), so that you can read it with any ordinary mail client. You can also redirect to any arbitrary external email address you own.

Warning: this only works if you're using PHP's built-in mail functionality. It won't help if you're talking directly to an SMTP server via something like PHPMailer.

Create a shell script with the following content:

/usr/sbin/sendmail -i "[email protected]" "$REDIRECT"

Make it executable, then add a line to php.ini:

sendmail_path = "/path/to/ [email protected]"

Reload Apache, and you're done.

(It might seem that you can simplify this further by putting the sendmail command directly in php.ini, but you can't: Postfix's sendmail expects its arguments in POSIX order (options first), and PHP may add a -f option after the hardcoded email address, which would be interpreted as a recipient address beginning with -f).

You can also redirect email to a different address for each virtual host, by setting the sendmail_path option via php_admin_value.

I've tested this with Postfix on Ubuntu, but I believe it should work in other configurations too.