How to send emails with the PHP mail() function

How to send emails with the PHP mail() function

The PHP mail() function is a built-in way to send emails directly from a PHP script.

Developers often use it for simple tasks like sending contact form messages or testing email functionality.

While it is easy to use, the mail() function has limitations that make it better suited for learning and small projects than for production environments.

What is the PHP mail() function?

The PHP mail() function lets your website send emails without needing an external library. It works by calling the web server’s mail transfer agent (MTA) to deliver messages.;

The function takes in at least three parameters: the recipient’s email, the subject line, and the message body. You can also include optional headers like From, Reply-To, and content type.

This makes mail() one of the quickest ways to test sending emails in PHP. However, it doesn’t offer modern features like authentication, attachments, or reliable spam protection.

PHPMailer vs mail() function: pros and cons

While mail() is simple, it lacks flexibility. PHPMailer, on the other hand, is a popular library that provides advanced email features like SMTP support, authentication, attachments, and HTML formatting.

Pros of mail():

  • Built into PHP
  • Easy to use
  • No installation required

Cons of mail():

  • Limited functionality
  • Higher chance of being flagged as spam
  • Harder to debug errors

If you need advanced features, consider using PHPMailer. We’ve covered it in detail in our guide on how to send emails using PHPMailer.

How to send emails using the PHP mail() function

Here’s the basic syntax of the mail() function:

mail(to, subject, message, headers, parameters);
  • to – the recipient’s email address.
  • subject – the email subject line.
  • message – the body of the email.
  • headers – additional information like From, Reply-To, or Content-Type.
  • parameters – optional extra options passed to the system’s sendmail program.

Understanding PHP mail components

To send an email successfully, you need to set up correct headers:

<?php
$to = "example@domain.com";
$subject = "Test email from PHP";
$message = "This is a plain text email example.";
$headers = "From: hello@domain.com" . "\r\n" .
           "Reply-To: hello@domain.com" . "\r\n" .
           "X-Mailer: PHP/" . phpversion();

mail($to, $subject, $message, $headers);
?>
  • From – sets the sender address.
  • Reply-To – defines where replies should be directed.
  • X-Mailer – identifies that the message was sent by PHP.

Creating a test file for PHP mail

To test mail(), create a testmail.php file in your server root:

<?php
$to = "youraddress@example.com";
$subject = "PHP Mail Test";
$message = "This is a test message sent from PHP.";
$headers = "From: webmaster@yourdomain.com";

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully.";
} else {
    echo "Email delivery failed.";
}
?>

Upload this file and access it in your browser. If configured correctly, you should receive an email.

Sending HTML emails with PHP

By default, mail() sends plain-text emails. To send HTML emails, add a Content-Type header:

<?php
$to = "example@domain.com";
$subject = "HTML Email Example";

$message = "
<html>
<head>
<title>HTML Email</title>
</head>
<body>
<h1>Hello!</h1>
<p>This is an <strong>HTML</strong> email sent with PHP.</p>
</body>
</html>
";

$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: hello@domain.com" . "\r\n";

mail($to, $subject, $message, $headers);
?>

This allows you to format text, add headings, and style your message with HTML.

How can I validate email addresses before using the PHP mail() function or PHPMailer to send emails?

Validating email addresses helps prevent errors and reduce spam issues. PHP provides filter_var() for this:

<?php
$email = "user@example.com";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email address.";
} else {
    echo "Invalid email address.";
}
?>

This ensures you only send emails to properly formatted addresses.

How to troubleshoot common PHP mail() function errors

The mail() function can fail for several reasons. Here are the most common issues:

  • Mail goes to the spam folder
  • Could not connect to SMTP host
  • Gmail couldn’t verify that domain.tld sent this message
  • Sender address rejected: not owned by the user
  • Mail not delivered at all (silently failing)
  • Incorrect headers or formatting

Mail goes to the spam folder

Emails often end up in spam if headers are incomplete or if the content looks suspicious. To reduce the risk:

  • Use a proper From address matching your domain.
  • Avoid trigger words that spam filters flag.
  • Set up DNS records like SPF and DKIM for domain verification.

Example of adding From and Reply-To headers:

$headers = "From: no-reply@yourdomain.com\r\n";
$headers .= "Reply-To: support@yourdomain.com\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();

Could not connect to SMTP host

This error indicates a server configuration problem. Possible causes include:

  • The hosting provider blocks outbound mail.
  • PHP mail is disabled in php.ini.
  • Firewall rules are preventing the connection.

Example of checking mail function in php.ini

; Make sure this is not disabled
disable_functions =

Gmail couldn’t verify that domain.tld sent this message

Gmail and other providers require domain authentication to trust your messages. To fix this, ensure you have the following TXT entries in your DNS records:

  • Add an SPF record to specify authorized mail servers.
  • Enable DKIM to verify message integrity.
  • Set up DMARC to protect against spoofing.

Example of an SPF record:

v=spf1 include:_spf.[domain.tld] ~all

Example of a DKIM record:

Name: [selector]._domainkey.[domain.tld]
Content: v=DKIM1; p=[series of numbers]

Example of a DMARC record:

Name: _dmarc.[domain.tld]
Content: v=DMARC1; p=none; rua=mailto:[yourname]@[domain.tld]

Sender address rejected: not owned by the user

This happens when the sender email does not belong to your domain. To resolve it:

  • Always use a valid sender address, like no-reply@yourdomain.com.
  • Avoid using third-party addresses such as Gmail or Yahoo in the From field.

Example of a correct sender address:

$headers = "From: no-reply@yourdomain.com\r\n";

Mail not delivered at all (silently failing)

Sometimes the mail() function does not throw an error but messages never arrive. Common reasons include:

  • The hosting provider blocks PHP mail for security reasons.
  • The server is misconfigured.
  • Logs show messages being dropped.

Example of logging mail() results in PHP

if (mail($to, $subject, $message, $headers)) {
    error_log("Mail sent successfully to $to");
} else {
    error_log("Mail failed to send to $to");
}

Incorrect headers or formatting

Improper headers cause delivery failures or corrupted emails. Follow these practices:

  • Always use \r\n for line breaks in headers.
  • Include MIME-Version and Content-Type when sending HTML emails.
  • Keep formatting consistent to avoid parsing errors.

Example of correct HTML headers:

$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";

When to move beyond the mail() function

The PHP mail() function is useful for learning, debugging, and sending simple test messages. However, it is not the best choice for production use. If you need reliable delivery, attachments, or SMTP authentication, move to a more powerful library like PHPMailer or connect to an external email service.

All of the tutorial content on this website is subject to Hostinger's rigorous editorial standards and values.

Author
The author

Matleena Salminen

Matleena is a seasoned Content Writer with 5 years of content marketing experience. She has a particular interest in emerging digital marketing trends, website building, and AI. In her free time, Matleena enjoys cups of good coffee, tends to her balcony garden, and studies Japanese. Follow her on LinkedIn