Having incorrect From field in email when sending with php

Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Having incorrect From field in email when sending with php

Post by Neo » Thu Mar 29, 2012 4:07 am

This is because you missed to specify "From" field in additional headers.

Have a look at following simple email example.

Code: Select all

<?php
    // The message
    $message = "Line 1\nLine 2\nLine 3";

    // In case any of our lines are larger than 70 characters, we should use wordwrap()
    $message = wordwrap($message, 70);

    // Send
    mail('[email protected]', 'My Subject', $message);
?>
This works perfectly but since we don't specify from where we need to send this email, it simply users what you have specified for sendmail_from in php.ini. In cases where you don't have access to php.ini (ex: shared hosting), this problem become worst as the host specify something automatic based on the server and user account. Having a local php.ini can sort this problem mostly but there is an easy way to get rid of this.

See this example:

Code: Select all

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers =    'From: [email protected]' . "\r\n" .
                'Reply-To: [email protected]' . "\r\n" .
                'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
Here we specify both From and Reply-To headers correctly and this will perfectly give you the expected results.

Here is the way to send email with HTML contents.

Code: Select all

<?php
    // multiple recipients
    $to  = '[email protected]' . ', '; // note the comma
    $to .= '[email protected]';

    // subject
    $subject = 'Birthday Reminders for August';

    // message
    $message = '
    <html>
    <head>
      <title>Birthday Reminders for August</title>
    </head>
    <body>
      <p>Here are the birthdays upcoming in August!</p>
      <table>
        <tr>
          <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
        </tr>
        <tr>
          <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
        </tr>
        <tr>
          <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
        </tr>
      </table>
    </body>
    </html>
    ';

    // To send HTML mail, the Content-type header must be set
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

    // Additional headers
    $headers .= 'To: Mary <[email protected]>, Kelly <[email protected]>' . "\r\n";
    $headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";
    $headers .= 'Cc: [email protected]' . "\r\n";
    $headers .= 'Bcc: [email protected]' . "\r\n";

    // Mail it
    mail($to, $subject, $message, $headers);
?>
If you find that the email is corrupted, replace "\r\n" with just "\n".
Post Reply

Return to “PHP & MySQL”