treehouse : what would you like to learn today?
Web Design Web Development iOS Development

How to send mails using PHP?

  • I tried the following code with my email as $to but I got the message from the else part.
    <html>
    <head>
    <title>Sending email using PHP</title>
    </head>
    <body>
    <?php
    $to = "xyz@somedomain.com";
    $subject = "This is subject";
    $message = "This is simple text message.";
    $header = "From:abc@somedomain.com \r\n";
    $retval = mail ($to,$subject,$message,$header);
    if( $retval == true )
    {
    echo "Message sent successfully...";
    }
    else
    {
    echo "Message could not be sent...";
    }
    ?>
    </body>
    </html>


    I got the code from here
    You can check the output here

    Can anyone tell me the corrections?

    What should be the config of the [mail function] in php.ini for Windows? How to change it on the server where the site is hosted? Please refer the first link for this config.

    Thanks
    MH
  • I don't know much about php for Windows, but this might be relevant. Hope that helps!
  • Couple of questions:
    1.) Are you trying to send via SMTP or PHP native mail() function?
    2.) Do you have an SMTP server setup on your windows box?

    Also, you're not providing the proper mail headers. You need:
    - version
    - content-type / charset
    - from
    - reply-to

    all which need to new line breaks for the native mail function. ie "\r\n".
  • Not sure if it matters, but there should be a space after the "From:" in your $header variable, and there should be no space before the \r\n. Also, keep in mind that a local server is not going to be able to send out mail (at least without special set up or additional software). If you want to test this legitimately, make sure you're running it on a live server.
  • Some times the mail() php function can be switched off as default by your hosting company in the php.ini file. One thing you can try to do is put a php.ini file in the same directory as the script and make sure that the mail() function is switched on in it. This sometimes might not work if the hosting company have set the server up to ignore other php.ini files.
  • One other thing you could do is put a php file on your server with just the phpinfo() function in it. It will list every function/extension that is switched on and off on your server, it can help solve a lot of issues.