Categories
email function html php

PHP mail function doesn’t complete sending of e-mail

544

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com';
    $to = '[email protected]';
    $subject="Customer Inquiry";
    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    if ($_POST['submit']) {
        if (mail ($to, $subject, $body, $from)) {
            echo '<p>Your message has been sent!</p>';
        } else {
            echo '<p>Something went wrong, go back and try again!</p>';
        }
    }
?>

I’ve tried creating a simple mail form. The form itself is on my index.html page, but it submits to a separate “thank you for your submission” page, thankyou.php, where the above PHP code is embedded.
The code submits perfectly, but never sends an email. How can I fix this?

5

  • 3

    is your program in local computer or live host

    Jul 9, 2014 at 2:20

  • 9

    1. are you sure it isn’t going into your spam? 2. do you have sendmail configured on your box?

    Jul 9, 2014 at 2:21

  • its on a live host it is not going into my spam..i’m not sure what you mean by having sendmail configured on my box so i assume not?

    Jul 9, 2014 at 2:22

  • 1

    try send without $from

    Nov 8, 2017 at 14:31

  • I’ve run into a similar problem before, and it wasn’t caused by any of the errors listed in the recommended answer below. It’s because my DNS lists another server as the authorised mail server, but the web server itself is configured to recognise itself as the authorised mail server too. So when PHP mail() sends emails to its own domain, it does not check the DNS records to find the correct mail server, and just forwards the email to itself. I’ve wrote an article about it detailing the fix: blog.terresquall.com/2021/04/…

    – John Doe

    Jan 15 at 16:09

44

Add a mail header in the mail function:

$header = "From: [email protected]\r\n";
$header.= "MIME-Version: 1.0\r\n";
$header.= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$header.= "X-Priority: 1\r\n";

$status = mail($to, $subject, $message, $header);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}

    26

    1. Always try sending headers in the mail function.
    2. If you are sending mail through localhost then do the SMTP settings for sending mail.
    3. If you are sending mail through a server then check the email sending feature is enabled on your server.