Correctly setting the return path on emails sent by PHP

Email commonly includes the sender’s address in two places. The From header in the message body is the one that most people are aware of, and this is the address that email recipients see. However, the sending mail server also adds a Return-Path before the message body. Recipients don’t generally see this address, but it is important for two reasons. First, it is used in a number of anti-spam checks. Second, it’s the address that typically receives non-delivery reports if a message can’t be delivered for any reason. PHP’s mail() function requires that the From address be set, but the Return-Path is usually not set, meaning that it stays as the default value. Annoyingly this seems to be the case in WordPress, as well as most bespoke code. For example, on our server the default might be The first part is the user that PHP scripts run as, and the second part is the web server’s primary hostname. Leaving this as the default can be a source of backscatter and a cause of messages ending up in their recipients’ junk folders.

There are three possible fixes. The first is to correctly call the mail() function and specify the Return-Path by passing the -f argument to the mail program. This is by far the best option. For example,

mail( '', 'Subject', 'Body', "From: <>\r\n", '' );

The second is to set the mail.force_extra_parameters ini setting, in a .htaccess file, a local php.ini or .user.ini file, or in the site’s global config. For example, in .htaccess:

<IfModule mod_php7.c>
    php_value mail.force_extra_parameters ""

The final option is to set the sendmail_path in the site’s global config. This is the least elegant solution, but if you’re hosting a site on someone else’s behalf that isn’t properly coded and you’re receiving backscatter as a result, it is your only real option. For example, in /etc/php7.0/fpm/pool.d/

php_admin_value sendmail_path = "/usr/sbin/sendmail -t -i"

Add new comment