Sending email with PHP

  1. Built-in mail() function

    PHP has a built-in function for sending email which makes it about as simple as could be to send text emails from your scripts.

    The built-in mail() function is documented both here: http://www.php.net/manual/en/function.mail.php
    and http://www.php.net/manual/en/ref.mail.php .

    It has the following syntax:

    bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]])

    For a moment let's pretend the optional 4th parameter doesn't exist...

    bool mail ( string to, string subject, string message)

    You are free to ignore the return value in your code (though this might not be a good idea) so sending email with PHP can be as simple as this:

    <?php

    $myMessage = "This is the message being sent.";
    mail ( " user@somedomain.com ", "Test message", $myMessage );

    ?>


    1. How to include a "From:" address

      The manual tells us about mail() , "If a fourth string argument is passed, this string is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers are separated with a carriage return and newline.

      Note: You must use \r\n to separate headers, although some Unix mail transfer agents may work with just a single newline ( \n )."

      An example is the " From: " header, used to include return address...

      <?php

      $myMessage = "This is the message being sent.";
      $myHeader = "From: webmaster@mydomain.com\r\n";
      // other headers could be added

      mail ( " user@somedomain.com ", "Test message", $myMessage, $myHeader );

      ?>

    2. Possible problems using the built-in mail() function...

      The mail() function is notoriously temperamental. The mail() function relies on PHP having access to an appropriate mail program on the server. If you are experiencing problems then the resolution might be as simple as updating your sever's php.ini file to point to the appropriate mail server software.


  2. You can see these recommended resources:

    http://www.zend.com/zend/spotlight/sendmimeemailpart1.ph
    http://pear.php.net/package/Mail_Mim
    http://www.phpbuilder.com/columns/kartic20000807.php