0

I am setting up a small webpage for a project and I had issues getting the inputs from the contact form to be sent to my email address. The code runs just fine, not prompting any errors but I am not receiving the email that the customer fills up on the contact form.

Could anyone advise? I am currently hosting it for free using infinityfree so does it affect the mail() function? Below is the .php code file I used for my backend.

<?php

$to = 'myemail@gmail.com';
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
$from = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$subject = filter_input(INPUT_POST, 'subject', FILTER_SANITIZE_SPECIAL_CHARS);
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_SPECIAL_CHARS);

if (filter_var($from, FILTER_VALIDATE_EMAIL)) {
    $headers = ['From' => ($name?"<$name> ":'').$from,
            'X-Mailer' => 'PHP/' . phpversion()
           ];

    mail($to, $subject, $message."\r\n\r\nfrom: ".$_SERVER['REMOTE_ADDR'], $headers);
    die('OK');
    
} else {
    die('Invalid address');
}

?>
DarkBee
  • 16,592
  • 6
  • 46
  • 58
chua
  • 1
  • 1
    1. What are the contents of `$_POST`? 2. Do you get output `OK`? 3. Does `mail` returns true? 4. Try using PHPMailer instead. `mail` is [not reliable](https://stackoverflow.com/questions/4565066/why-shouldnt-i-use-phps-mail-function) to use. – Justinas Oct 14 '22 at 07:37
  • 2
    Does this answer your question? [PHP mail function doesn't complete sending of e-mail](https://stackoverflow.com/questions/24644436/php-mail-function-doesnt-complete-sending-of-e-mail). But first do the basic debugging that Justinas suggested, to ensure your code actually reaches the mail function and passes in the values you were expecting – ADyson Oct 14 '22 at 07:39
  • Did you check emails on `SPAM` box? or did you successful send an email on your local?. Please also check your hosting config to able to send email. https://www.quackit.com/php/tutorial/php_mail_configuration.cfm – Binh Ho Oct 14 '22 at 07:59
  • 1
    You can't just use a "faux" from anymore. See the duplicated psot – DarkBee Oct 14 '22 at 08:16
  • 1
    Don't use the low-level `mail()` function that is dependent on the server's configuration. Use some mail library like PHPMailer and always send it from your email address (you're the actual sender, not the user filling in the form) and send it through your email addresses SMTP server. Right now, you're spoofing their addresses, which many spam filters and mail servers pick up on. – M. Eriksson Oct 14 '22 at 08:20

0 Answers0