Can someone help me, my contact form does not working. It will send successfully, but the email recipient can't receive the message. Here is my code:

<?php

$email_to =   'name@example.com'; //the address to which the email will be sent
$name     =   $_POST['name'];  
$email    =   $_POST['email'];
$subject  =   $_POST['subject'];
$message  =   $_POST['message'];

$headers = 'From:' . $email;

if(mail($email_to, $subject, $message, $headers)){
    echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent..      
}else{
    echo 'failed';// ... or this one to tell it that it wasn't sent    
}

?>

Firstly, I'd suggest you edit your post to remove your real email address from the code.

https://www.php.net/manual/en/function.mail.php

Some things to try.

  1. Headers is an optional parameter, can you send without the headers parameter? Many examples I've seen suggest there should be a space after the :, as in 'From: '
  2. Sanitise your subject and/or message. You can't in general feed whatever was typed into your dialog directly into mail.

Does a very simple inline code work?
mail('my@my.address.com','Testing...','1 2 3');

Firstly, I'd suggest you edit your post to remove your real email address from the code.

I have replaced their email address with a dummy email.

Sanitise your subject and/or message. You can't in general feed whatever was typed into your dialog directly into mail.

Salem is referring to passing each of those variables in htmlspecialchars() to make sure there is not any HTML or Javascript embedded in the strings that could potentially be executed. Or, alternatively, you can use PHP's filter_var() function to sanitize user input.

WEB security now rejects mail sent from any computer. Select some mail provider and send mail using it. Using certificated WEB serve is an another solution. Obtain legal certificate, register it on WEB server (IIS, Apache, NGINX, ...)

commented: I tried a test mail, and it was ok. I think my code is the problem +0

I'm not entirely sure what gediminas is referring to, but there are services out there such as Zoho Mail, SendGrid, ConstantContact, Mailchimp, Hostinger, etc. which, for the most part, cost money (some are rather inexpensive), but the benefit to using them is that they ensure you're never sending emails to non-existant email addresses, email addresses that bounce, and that emails always make it to their intended recipient.

If you're not getting any PHP errors, it's possible that your outgoing mail server is not configured properly on your web server.

commented: I tried a test mail, and it was ok. I think my code is the problem +0

Reducing spam bots I strongly suggest to use SMTP, I would prefer to use PHPMailer which get more secure and handle professionally templates.

It was a time when anybody could to send a mail from Apache (or IIS) installed on local computer but internet spammers have used that feature for evil purposes. Now you can send emails from an officially registered server only. Even if you manage to send a letter somehow it will not reach the recipient or will be automatically will be placed into the trash. Free mailing is available on local network only.

Apart from doing some protection to your code, it will more than likely be your ISP not allowing the mail function to work. We have had to get an email acct with permissions allocated to each websites form by our providers.

Emailing became more restrictive in the last year, so when you have a PHP server with no emailing setup the emails often fail completely now as there is so much wasted bandwidth on spam emails that these get turned down instantly.

I solved it on my hosting with the PHPmailer package, it's maybe a bit of a headache if you are not that familiar with using PHP but you can get it to work without needing server admin access. You will need an SMTP account to login to so you can send out emails(like the malbox login on your email client, outlook, thunderbird, gmail etc.)

Be careful with the password and make sure you properly sanitize any user inputs so the email sending can't be abused.

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'includes/PHPMailer/src/Exception.php';
require 'includes/PHPMailer/src/PHPMailer.php';
require 'includes/PHPMailer/src/SMTP.php';

date_default_timezone_set('Etc/UTC');

//$remoteaddr = $_SERVER["REMOTE_ADDR"];
//$user_agent = str_replace("'", '"', $_SERVER["HTTP_USER_AGENT"]);

/* Create a new PHPMailer object. Passing TRUE to the constructor enables exceptions. */
$mail = new PHPMailer(TRUE);
/* Open the try/catch block. */
try {
    /* Set the mail sender. */

    $mail->CharSet = "UTF-8";
    $mail->Encoding = 'base64';
    $mail->isSMTP();
    $mail->Host       = 'mail.example.com';     //Set the SMTP server to send through
    $mail->SMTPAuth   = true;
    $mail->SMTPSecure = 'tls';
    $mail->Username   = 'email@example.com';    //SMTP username
    $mail->Password   = 'your password';        //SMTP password
    $mail->Port       = 587;                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

    $mail->setFrom('email@example.com', 'Example.com website');
    /* Add a recipient. */
    $mail->addAddress('test@example.com');
    /* Set the subject. */
    $mail->Subject = 'Survey Form filled out';
    /* Set the mail message body. */
    $mail->Body = 'some message';
    /* Finally send the mail. */
    $mail->send();

}
catch (Exception $e)
{
   /* PHPMailer exception. */
   echo $e->errorMessage();
}
?>

Emailing became more restrictive in the last year

Are you referring to SPF, DKIM, and DMARC?

Damn, you caught me out on that! I went generalized cause I forgot what it was that happened.

But I dug it up: Google Search:Gmail email restriction in Feb 2024

Is what I was thinking of - but I think my web hosting providors were also complaining about my badly setup emails being sent out via the mail function - as the PHP server was not setup correctly and I was not an admin. the PHP mailer package solved the problem though

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.