Mail function is not working in PHP

Mail function is not working in PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Why mail() Fails and How to Fix It

The provided PHP script attempts to send an email using the built-in mail() function, but it consistently reports failure even though the form data is being received correctly. This specific behavior—printing "failed" immediately after submission—is a classic symptom of missing server configuration rather than a logic error in your PHP code. The mail() function does not connect to an SMTP server and send messages over the network; it simply hands off an email message to the local operating system's Mail Transfer Agent (MTA), such as Postfix, Exim, or Sendmail. If that MTA is not installed, not running, or misconfigured, mail() returns false.

The most immediate hurdle in the provided code snippet is the reliance on deprecated security functions. You are using mysql_real_escape_string() for data sanitization. This function belongs to the old MySQL extension, which has been removed from standard PHP distributions years ago. While this specific line doesn't cause the email failure directly, it indicates a codebase that requires immediate modernization. Switching to PDO or prepared statements is non-negotiable for any production environment due to SQL injection vulnerabilities and the lack of support for modern databases.

To resolve the "failed" status, you must verify your server environment first. If you are running PHP on a fresh Linux installation (like Ubuntu or CentOS) without explicitly installing and configuring an MTA like Postfix or Exim, mail() will almost certainly fail. You can test this by installing Postfix:

sudo apt-get install postfix

After installation, ensure the service is active:

sudo systemctl status postfix

Without this step, the system has no way to route the message to the internet. However, relying on a local MTA for web applications is often an anti-pattern, especially if you don't own the domain associated with the destination address.

A more robust and standard approach for web-based email sending is to use SMTP directly via PHP's phpmailer library or native stream_socket_client. This bypasses the OS-level mail queue entirely and connects directly to your hosting provider's SMTP server (e.g., Gmail, cPanel, AWS SES). Here is a basic example using PHPMailer, which handles headers, authentication, and connection details much more reliably than mail():

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com'; // Or your host's SMTP server
    $mail->SMTPAuth   = true;
    $mail->Username   = 'your_email@gmail.com';
    $mail->Password   = 'your_password_or_app_specific_key';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    // Recipients
    $mail->setFrom('your_email@gmail.com', 'Your Name');
    $mail->addAddress('admin@gmail.com', 'Admin');

    // Content
    $name = trim($_POST['name']);
    $phone = trim($_POST['phone']);
    
    $mail->isHTML(true);
    $mail->Subject = 'Customer Interested';
    $mail->Body    = "Buyer Information and Interested in land.<br><br>";
    $mail->Body    .= "Customer Name : $name<br>";
    $mail->Body    .= "Customer Phone : $phone";

    $mail->send();
    echo "success";
} catch (Exception $e) {
    echo "Mailer failed to send. Error: {$mail->ErrorInfo}";
}

This approach is superior because it provides explicit error messages if authentication fails or if the port is blocked, whereas mail() often just returns false with no diagnostic information. Additionally, this method works on shared hosting environments where Postfix might be restricted.

Finally, ensure your PHP configuration allows sending mail. In older versions of PHP (pre-7.0), there was a strict requirement that the sendmail_path directive in php.ini must point to a valid MTA binary. If this path is empty or invalid, mail() will fail silently or explicitly. Check your logs (/var/log/mail.log or /var/log/maillog) for errors like "unable to connect" or "permission denied" if the switch to SMTP is not viable.

If you are building a larger application and want to avoid reinventing the wheel, consider leveraging frameworks that abstract these complexities away. Tools like Laravel provide robust mail drivers that handle queueing, logging, and multiple transport mechanisms seamlessly. For more details on implementing reliable background jobs and queue systems in PHP applications, you can explore resources at https://laravelcompany.com.

Our network