-2

I am trying to get a contact form using the built in mail function to work but I'm running into some problems.

What I would like:

  • On clicking 'submit' the form is sent to defined emailadres.php.
  • If sent successfully, a confirmation message is displayed.
  • If not sent, an error message is displayed.

What is currently happening:

  • Confirmation message already shows on page load; regardless of form submission.
  • Mail is not sent.

Code I'm using:

if ($_POST["submit"]) {
    mail ($to, $subject, $body, $from); 
    $sendErr = "Your message has been sent";
} else {
    $sendErr = "Your message could not be sent";
}

I'm fairly new to all this so any help figuring out where my thinking stalls would be appreciated. If I need to post more parts of the form I will.

JustCarty
  • 3,839
  • 5
  • 31
  • 51
Woodman
  • 11
  • 1
  • 5
  • first seach it https://stackoverflow.com/questions/5335273/how-to-send-an-email-using-php – Álvaro Touzón Oct 16 '17 at 08:14
  • 1
    you need [this](https://github.com/PHPMailer/PHPMailer) library – hungrykoala Oct 16 '17 at 08:15
  • 1
    Confirmation message is showing because you have put success message if the user clicks on submit. Whether your mail function runs or not the success message will be displayed. if you are running this on local server then it wont work u need to install mail server. – Ramu Bhusal Oct 16 '17 at 08:21
  • As @hungrykoala said, use PHPMailer, it is incredibly powerful – JustCarty Oct 16 '17 at 08:33
  • BTW: If you are using php mail(), your recipients may not get your email on the first attempt as of Greylisting. I propose to use a framework or a smtp-server instead of just php's inbuilt function. – inetphantom Oct 16 '17 at 08:34
  • I'm looking into it right now, thanks – Woodman Oct 16 '17 at 08:45

1 Answers1

1

The code you are using does not even check if the mail was sent successfully, it only checks it the formular was submitted. mail() returns true if the mail was sent successfully, false if not. So you can check its return value:

if ($_POST["submit"]) {
    $sent = mail ($to, $subject, $body, $from); 

    // Check here if the mail was sent or not
    if ($sent) {
        $sendErr = "Your message has been sent";
    } else {
        $sendErr = "Your message could not be sent";
    }
}
Manuel Mannhardt
  • 2,191
  • 1
  • 17
  • 23