emersonthis
emersonthis

Reputation: 33378

PHP mail() with From: header prevents delivery

First things first... I know mail deliverability is effected by hundreds of factors and so it's never possible to say for SURE if one specific thing is the cause. (I do not expect this.)

My question is whether is normal/expected for mail servers to block messages which have a different From: header. My contact form handler uses this so that the reciptient can reply to the sender (code below). Gmail accounts are able to receive the messages. But my client has an institutional .edu email address and the emails aren't getting delivered.

Here's a minimal version of my code:

<?php 

$first_name = 'John';
$last_name = 'Smithy';
$email = "[email protected]";
$msg = "This is a test email. If you received it things are working.";

$test_email = (isset($_POST['test_email'])) ? $_POST['test_email'] : FALSE;

$to;
$from = $email;
$subject = "Contact from JamesGregoryMD.com";
$body = wordwrap( "{$first_name} {$last_name}:\n\n{$msg}\n\n{$email}\n{$phone}", 70);
$headers = "From: {$from}" . "\r\n";

if ($test_email) {
    # send email
    $return = mail($test_email,"Test email",$body, $headers);

    if ($return) {
        echo "<h1>MAIL SENT</h1>";
    } else {
        echo "<h1>MAIL NOT SENT</h1>";
    }
}
?>

<form id="contact" method="post">
    <input type="email" name="test_email" placeholder="email" />
    <input type="submit" value="Send" />
</form>

Upvotes: 0

Views: 102

Answers (2)

haliphax
haliphax

Reputation: 393

Use the Reply-To: header instead of From: and you likely won't have that problem (but will get the same functionality).

Upvotes: 1

IMSoP
IMSoP

Reputation: 97718

What you are effectively doing is "spoofing" the From address. This is perfectly acceptable according to the definition of SMTP, but only because when the Internet was young, nobody thought that it would be abused. Unfortunately, this leaves the door wide open to spammers, so various checks are generally implemented which you may be running into:

  • When connecting to an SMTP server (to deliver mail to a user on that domain), the client sends a "HELO" (or extended "EHLO") message with their identity. Some servers will reject messages where this doesn't match the From header. Depending on the setup, you may get some joy be adding "-f$from_address" as the 5th parameter to the mail() function.
  • Other servers may verify that you're actually connecting from the domain mentioned in that parameter, so still won't like it.
  • More sophisticated systems will check DNS records on the domain of the from address for allowed sender information. Look up "SPF" and "DKIM" online and you should find info on how to check and set them up.

Upvotes: 1

Related Questions