This is a website by Willem van Zyl

I'm a project manager, software developer, Apple evangelist and geek from South Africa. I'm passionate about web and mobile application development, usability, productivity, physics, astronomy, science fiction and fantasy.

If you would like to contact me, message me on Twitter or send me an email.

How to force a "Return-Path" header when sending email with PHP's mail() function

19 Feb 2009

When sending emails with PHP's mail() function, you are able to specify headers such as Content-type, To, From and Return-Path:

<?php

  $headers  = "MIME-Version: 1.0\r\n";
  $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
  //$headers .= "To: Myself <recipient@domain.com>\r\n";
  $headers .= "From: Willem <sender@domain.com>\r\n";
  $headers .= "Return-Path: sender@domain.com\r\n";

  $mail_body = "This<br />is<br />a<br />test<br />mail.";

  mail('recipient@domain.com', 'Subject', $mail_body, $headers);

?>

Depending on sendmail's configuration your Return-Path might be overridden by the default setting for the machine, and the raw source of the sent message will contain something like:

Return-Path: <_www@willem-macbook-pro.local>

... instead of:

Return-Path: <sender@domain.com>

If this happens, some email servers will not accept the message because the Return-Path domain can't be verified. To force the correct Return-Path use the mail() function's fifth argument to specify extra options that must be passed to sendmail:

mail('recipient@domain.com', 'Subject',
  $mail_body, $headers, " -f sender@domain.com");
Do you like this? Share it:

Copyright © Geekology 2011. All Rights Reserved.

Hosted by Code. Like. Clockwork.