Biggest deals of the year. 30-day money-back guarantee. Limited time deals. 24/7 support. Don't miss out

How to send emails with the PHP mail() function

Last updated 7 min Read
How to send emails with the PHP mail() function

Find the right learning path for you

  • Free resources
  • Practical tutorials
  • Helpful tools
Explore

The PHP mail() function sends an email directly from a PHP script by passing the message to the server’s mail system, with no external library to install. You call mail() with a recipient, a subject, and a message, then add headers for the sender, reply address, copies, or HTML content.

This guide covers the mail() syntax and headers, a test script that confirms your server can send email, and examples for HTML emails and contact form messages. It also explains how to fix common problems, such as messages landing in spam, missing SPF, DKIM, and DMARC records, and disabled mail functions.

Because mail() has no SMTP authentication, it works best for testing and low-volume notifications. The final section compares mail() with PHPMailer and explains when to switch.

What is the PHP mail() function?

The PHP mail() function is a built-in function that sends an email directly from a PHP script. Because mail() is part of the core PHP scripting language, there’s no library to install, which makes it a quick option for contact form notifications and test messages.

The mail() function doesn’t deliver email by itself. On Linux servers, it passes each message to the local mail transfer agent (MTA), such as Sendmail, Postfix, or Exim, through the program set in the sendmail_path directive of php.ini. On Windows, mail() connects to the SMTP server set in the SMTP and smtp_port directives.

The function requires three parameters: the recipient’s address, the subject line, and the message body. It returns true when the server accepts the message for delivery, which doesn’t confirm that the email reached the inbox.

The mail() function has no built-in SMTP authentication, attachment helper, or detailed error reporting, so deliverability depends on how the server is configured. That’s why mail() suits learning, testing, and low-volume notifications better than production email.

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.

Setting email headers, CC, and BCC

Headers tell mail clients who sent the message, where replies go, and who else receives a copy. Pass them as the fourth parameter, separated by \r\n:

<?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" .
           "Cc: manager@domain.com" . "\r\n" .
           "Bcc: archive@domain.com" . "\r\n" .
           "X-Mailer: PHP/" . phpversion();

mail($to, $subject, $message, $headers);
?>
  • From – sets the sender address. mail() needs a From header, or a sendmail_from default in php.ini.
  • Reply-To – defines where replies should be directed.
  • Cc – sends a visible copy to another recipient.
  • Bcc – sends a hidden copy that other recipients can’t see.
  • X-Mailer – identifies that the message was sent by PHP. This header is optional.

To send the same message to several main recipients, separate their addresses in $to with commas, for example “anna@domain.com, ben@domain.com”.

Creating a test file for PHP mail

A test file confirms whether mail() can hand messages to your server’s mail system. Create a testmail.php file in your website’s root directory:

<?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 accepted for delivery.";
} else {
    echo "Email was not accepted. Check your server's mail configuration.";
}
?>

Replace both addresses with real ones, using an address on your own domain in the From header. Upload the file to your web server, open https://yourdomain.com/testmail.php in your browser, and check both the inbox and the spam folder of the recipient address.

“Email accepted for delivery” only means the server took the message, not that it arrived. If nothing arrives within a few minutes, work through the troubleshooting steps for spam filtering and domain authentication. Delete testmail.php after testing so nobody else can use it to send messages.

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.

Sending contact form messages with mail()

A contact form sends visitor input to a PHP script, which validates it and passes it to mail(). Validation stops malformed addresses and blocks header injection, where an attacker adds line breaks to a field to insert extra recipients and turn your form into a spam relay.

Add this form to any page on your site:

<form action="contact.php" method="post">
  <input type="text" name="name" placeholder="Your name" required>
  <input type="email" name="email" placeholder="Your email" required>
  <textarea name="message" placeholder="Your message" required></textarea>
  <button type="submit">Send</button>
</form>

Then create contact.php in the same directory:

<?php
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    http_response_code(405);
    exit("Method not allowed.");
}

$name    = trim($_POST["name"] ?? "");
$email   = trim($_POST["email"] ?? "");
$message = trim($_POST["message"] ?? "");

// Reject empty fields, invalid addresses, and line breaks used for header injection
if ($name === "" || $message === "" || !filter_var($email, FILTER_VALIDATE_EMAIL) || preg_match("/[\r\n]/", $name)) {
    exit("Please enter your name, a valid email address, and a message.");
}

$to      = "you@yourdomain.com";
$subject = "New contact form message from " . $name;
$body    = "Name: " . $name . "\r\n" .
           "Email: " . $email . "\r\n\r\n" .
           wordwrap($message, 70, "\r\n");
$headers = [
    "From"         => "no-reply@yourdomain.com",
    "Reply-To"     => $email,
    "Content-Type" => "text/plain; charset=UTF-8",
];

if (mail($to, $subject, $body, $headers)) {
    echo "Thanks! Your message has been sent.";
} else {
    echo "Sorry, your message couldn't be sent. Please try again later.";
}
?>

The From header stays on your own domain, while Reply-To holds the visitor’s address, so you can answer with one click without failing sender checks. The filter_var() function with FILTER_VALIDATE_EMAIL rejects badly formatted addresses, and the header array format requires PHP 7.2 or later. For a public form, also add a CAPTCHA or a hidden honeypot field to reduce automated spam submissions.

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
  • Call to undefined function mail() or failed to connect to mailserver
  • 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();

Call to undefined function mail() or failed to connect to mailserver

Call to undefined function mail() or failed to connect to mailserver

These errors mean PHP can’t hand the message to a mail server. Since PHP 8.0, a function listed in the disable_functions directive behaves as if it doesn’t exist, so a disabled mail() triggers a fatal “Call to undefined function mail()” error. On Windows and local development setups, a warning such as “Failed to connect to mailserver at “localhost” port 25″ means no SMTP server is listening at the address set in php.ini.

To fix the problem:

  • Run var_dump(function_exists(“mail”)); in a PHP file. A false result means mail() is disabled.
  • On a server you manage, remove only mail from the disable_functions list in php.ini, then restart PHP. On shared hosting, ask your provider, because the main php.ini is managed for you. Hostinger keeps mail() enabled on its hosting servers.
  • On Windows or a local setup, point the SMTP and smtp_port directives to a reachable SMTP server, or set sendmail_path to a sendmail-compatible program.
  • Check whether a firewall or your provider blocks outbound connections on port 25.

Example of removing only mail from the disabled functions list in php.ini:

; Before: mail() is disabled
disable_functions = exec,shell_exec,system,mail

; After: only mail is removed from the list
disable_functions = exec,shell_exec,system

Never clear the whole disable_functions directive. An empty value turns back on every function the host disabled for security reasons, such as exec and shell_exec.

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

Gmail shows this warning when a message fails domain authentication. It’s common with mail() because the message leaves through the hosting server instead of your domain’s email service, so it may not carry your domain’s DKIM signature. To fix it, publish these TXT records in the DNS zone of the domain used in your From address:

  • 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 (use the include value your email or hosting provider gives you):

v=spf1 include:[provider SPF domain] ~all

Example of a DKIM record (your email provider generates the key and gives you the public key value):

Name: [selector]._domainkey.[domain.tld]
Content: v=DKIM1; k=rsa; p=[public key]

Example of a DMARC record:

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

Our guide to SPF, DKIM, and DMARC records explains how receiving servers check each record. If Gmail still shows the warning after the records are in place, send through authenticated SMTP instead, so messages leave from your domain’s mail server.

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 should you switch from mail() to PHPMailer?

Switch from mail() to PHPMailer or another SMTP-based library when you need reliable inbox delivery, attachments, SMTP authentication, or regular sending volume. The mail() function remains a good fit for learning, testing, and occasional notifications on a server with a working mail system.

FeaturePHP mail()PHPMailer with SMTP
SetupBuilt into PHPInstalled with Composer or manually
AuthenticationNone; relies on the server’s mail systemSMTP username and password
HTML emailManual MIME-Version and Content-Type headersBuilt-in isHTML() method
AttachmentsManual MIME encodingBuilt-in addAttachment() method
Error reportingReturns only true or falseDetailed error messages and SMTP debug output
DeliverabilityMore likely to be filtered as spamUsually better, because messages come from an authenticated mailbox
Best forTests and low-volume notificationsContact forms, transactional email, and production sites

Verdict: use mail() to check that your server can send email or to power a low-traffic form, and move to PHPMailer with SMTP as soon as delivery matters. On Hostinger web hosting, emails sent with mail() and other unauthenticated methods are limited to 10 per minute and 100 per day, and Hostinger recommends SMTP for regular sending.

To set up authenticated sending, follow our tutorial on how to send emails using PHPMailer, which covers installation, SMTP settings, and attachments.

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

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

Trusted by 4+ million website owners worldwide

See our 74,697 reviews on Trustpilot

Not sure which plan to choose?

Our smart AI agent, is here to help you find the best package for your project.

See Pricing