Postfix Ignores PHP mail() function
mail($to, $subject, $message, $headers,'From: ' . $fromname . ' <'.$from.'>', "-f $from -r [email protected]");
Cannot work as mail() only accepts 5 parameters: bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )
For me both
mail($to, $subject, $message, null, "-r [email protected]");
mail($to, $subject, $message, 'Name <[email protected]>', "-r [email protected]");
work (I don't have any additional restrictions in postfix which might rewrite senders). Also make sure that the sender is properly formatted (no spaces or whatsoever).
However, I recommend to adjust the sendmail_path
setting in your php.ini to include the "-r [email protected]" parameter.
If it doesn't work for you, you should post the mail headers here and check your log files for warnigns/errors.
PS: Please make sure you don't pass user entered data directly to mail()
, because if users can insert newlines (such as \nCC: [email protected]
in subject, to mail or from mail) your server might be used for spamming.
You could let the Postfix do its job rewriting headers and adding proper From:
addresses. For this, Postfix has sender_canonical_maps
.
Let's say your web server (or a process manager) runs under user named username
, and you want to have [email protected]
in the From:
header of your emails instead of unclear [email protected]
. Then, canonical map would contain:
#/etc/postfix/canonical
username [email protected]
Configuring Postfix to use it can't be easier:
postmap /etc/postfix/canonical
postconf -e sender_canonical_maps=hash:/etc/postfix/canonical
Other option is to tell postfix to mark all emails send from you server as send from [email protected]
by means of luser_relay
:
postconf -ev [email protected]
If you can't do it, quite possible someone already did this for you, but did that wrong. That could be a reason why you can't change From:
address since it is being forcedly overwritten by Postfix.
You've got the header argument in your mail()
call twice and thus, your $additional_parameters
argument isn't being used because it's the 6th argument in a function that only accepts 5. You should instead move the header to be included with the rest of your headers:
//Be mindful to protect from email injection attacks.
$fromname = str_replace("\n", "", $fromname);
$from = str_replace("\n", "", $from);
//This assumes that $headers is already set, containing your other headers
$headers .= 'From: ' . $fromname . ' <'.$from.">\n";
mail($to, $subject, $message, $headers, "-f $from -r [email protected]");
Using this, I would expect that your 5th argument is now redundant and could be simplified to:
$fromname = str_replace("\n", "", $fromname);
$from = str_replace("\n", "", $from);
$headers .= 'From: ' . $fromname . ' <'.$from.">\n";
mail($to, $subject, $message, $headers);