PHP Mail

Beginner
8 min read
Updated: Nov 2026
3 examples
mail(), headers & safety

Definition and Usage

PHP can send plain email with one built-in function, mail(). You give it the recipient, a subject, a message body, and optional headers. PHP does not talk to the recipient's mail server itself. It hands the message to the mail system that php.ini points to, such as a local sendmail program or an SMTP server, and that system does the real delivery.

Headers such as From and Reply-To control who the message appears to come from and where replies go. Because headers are plain text lines, any user input that lands in a header needs care. A line break in the wrong place lets an attacker add headers of their own. This is called header injection, and the fix is to validate every value before it reaches mail().

The mail extension has only two functions: mail() to send a message and ezmlm_hash(), a small helper for EZMLM mailing lists that was removed in PHP 8.0.

This page explains the ideas. The Mail Functions index lists both function guides.

Pick the right tool.

Use mail() for simple plain-text messages such as a contact-form notice. For HTML email, attachments, or SMTP login, use a mail library. Use ezmlm_hash() only if you maintain an EZMLM list on an old PHP version.

true does not mean delivered.

mail() returns true when the message was accepted for delivery by the local mail system. The message can still bounce, be filtered as spam, or never leave the server. Treat true as "handed off", not "received".

Local servers rarely send mail.

On a development machine with no mail system configured, mail() usually returns false or accepts the message and drops it. Point php.ini at a test SMTP catcher, or use the dry-run style in the examples below while you build and test your message.

PHP Syntax

The usual pattern: build the pieces, then make one mail() call and check the result:

PHP
// bool: true when the message is accepted for delivery
$accepted = mail(
    '[email protected]',                 // to
    'Order 1042 shipped',               // subject
    "Your order has shipped.",          // message
    [                                   // additional headers (PHP 7.2+)
        'From'         => 'CodeToFun <[email protected]>',
        'Reply-To'     => '[email protected]',
        'Content-Type' => 'text/plain; charset=UTF-8',
    ]
);

if (!$accepted) {
    error_log('mail() could not hand off the message');
}

// int: EZMLM hash of an address (removed in PHP 8.0)
// $hash = ezmlm_hash('[email protected]');

Core Ideas

What to remember when you send email from PHP:

IdeaFunction or settingRemember
Send a messagemail()Arguments are to, subject, message, headers, parameters; it returns a bool
Who it is fromFrom headerUse an address on a domain you control, or spam filters may reject the message
Where replies goReply-To headerPut the visitor's address here, not in From, when you relay a contact form
Message formatContent-Type headerUse text/plain; charset=UTF-8 for text; keep body lines to about 70 characters with wordwrap()
Return valuetrue / falsetrue means accepted for delivery, not delivered
Mail systemsendmail_path / SMTPSet in php.ini; without it mail() has nowhere to send
Safetyfilter_var()Validate addresses and reject line breaks in every header value
EZMLM listsezmlm_hash()Returns the hash used to name an address's subscriber file; removed in PHP 8.0

Header lines and the body

An email message is a block of header lines, one empty line, and then the body. mail() builds the To and Subject lines for you, and the fourth argument adds the rest. Separate header lines with a carriage return and line feed (\r\n), or pass an array and let PHP do it. The body is the third argument, and each line in it should stay short.

What ezmlm_hash() is for

EZMLM is an old mailing-list manager. It stores each subscriber in a file named after a hash of the address, so lists with many members stay fast. ezmlm_hash() computes that same hash for an address. It only matters if your code reads or writes EZMLM subscriber files directly. Since PHP 8.0 the function no longer exists, and nothing else in the language needs it.

php.ini Settings for mail()

mail() works only when php.ini tells PHP where to send the message. The settings differ by operating system. Restart the web server or PHP-FPM after you change them.

SettingPlatformWhat it does
sendmail_pathLinux, macOSThe sendmail-compatible program PHP runs, for example /usr/sbin/sendmail -t -i
SMTPWindowsHost name or IP address of the SMTP server PHP connects to
smtp_portWindowsPort of that SMTP server, usually 25
sendmail_fromWindowsDefault sender address when the message has no From header
mail.logAllWrites a line to a file for every mail() call, which helps when you debug "sent but missing" email
PHP cannot log in to SMTP for you.

The built-in SMTP setting does not support a user name and password. For an SMTP service that needs login, route sendmail_path through a relay tool or use a mail library that speaks SMTP itself.

Header Injection Risk

Headers are lines of text, so a carriage return or line feed inside a value starts a new header. If a contact form puts the visitor's email straight into Reply-To, a visitor can send an address followed by a line break and Bcc: [email protected]. Your server then mails everyone on that list.

Risky placeDefence
To, From, Reply-To valuesCheck with filter_var($value, FILTER_VALIDATE_EMAIL); it rejects line breaks
Subject textReplace every run of whitespace, including line breaks, with one space
Names in From or Reply-ToStrip line breaks and quotes, or leave the name out
Fifth argument (additional_params)Never pass user input; if you must, use escapeshellarg() on a validated address
Validate, do not just trust the form.

A browser form with type="email" is only a hint. Anyone can post anything to your script, so run the checks in PHP on every request.

PHP Examples

Three short scripts that show how to prepare and send mail. None of them needs a live mail server, so the output is the same every time you run it.

Example 1 — Shape the headers and body for mail()

Build the recipient, subject, headers, and a wrapped body, then print the message exactly as mail() would receive it. The real call stays as a comment so you can run the script anywhere.

PHP
<?php
$to      = '[email protected]';
$subject = 'Order 1042 shipped';
$text    = 'Hello Asha, your order 1042 has shipped. It should arrive within three working days.';
$body    = wordwrap($text, 40, "\r\n", true);

$headers = [
    'From'         => 'CodeToFun <[email protected]>',
    'Reply-To'     => '[email protected]',
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/plain; charset=UTF-8',
];

// Real call, left out so the script needs no mail server:
// $accepted = mail($to, $subject, $body, $headers);

echo "To: $to", PHP_EOL;
echo "Subject: $subject", PHP_EOL;
foreach ($headers as $name => $value) {
    echo "$name: $value", PHP_EOL;
}

$lines = explode("\r\n", $body);
echo "Body lines: ", count($lines), PHP_EOL;
foreach ($lines as $line) {
    echo "  | $line", PHP_EOL;
}
echo "Longest line: ", max(array_map('strlen', $lines)), PHP_EOL;
?>
mail() Tutorial

How It Works

  1. mail($to, $subject, $body, $headers) takes the recipient, subject, message, and headers in that order. Since PHP 7.2 the headers can be an array of name => value pairs, and PHP joins them with the right line endings.
  2. From sets the sender shown to the reader and Reply-To sets where a reply goes. Keeping them separate lets the visible sender stay on your own domain.
  3. wordwrap($text, 40, "\r\n", true) breaks the body into short lines. Mail standards ask for lines of about 70 characters or fewer; 40 is used here only to make the wrap easy to see.
  4. Content-Type with charset=UTF-8 tells the mail client how to read the text, which matters as soon as the body has accented or non-Latin characters.

Example 2 — Clean header input before it reaches mail()

Check three addresses and clean one subject. This is the guard that stops header injection, and it runs without sending anything.

PHP
<?php
$addresses = [
    '[email protected]',
    "[email protected]\r\nBcc: [email protected]",
    'not-an-email',
];

foreach ($addresses as $address) {
    $valid = filter_var($address, FILTER_VALIDATE_EMAIL) !== false;
    echo addcslashes($address, "\r\n"), ' => ', $valid ? 'ok' : 'rejected', PHP_EOL;
}

$subject = "Hi\r\nBcc: [email protected]";
$clean   = trim(preg_replace('/\s+/', ' ', $subject));

echo 'Raw subject: ', addcslashes($subject, "\r\n"), PHP_EOL;
echo 'Clean subject: ', $clean, PHP_EOL;
echo 'Has line break: ', preg_match('/[\r\n]/', $clean) ? 'yes' : 'no', PHP_EOL;
?>
mail() Tutorial

How It Works

  1. filter_var($address, FILTER_VALIDATE_EMAIL) returns the address when it is valid and false otherwise. An address with a line break and an extra Bcc: line is not a valid address, so it is rejected.
  2. addcslashes($value, "\r\n") prints the hidden carriage return and line feed as visible \r and \n, so you can see what the attacker sent. It is only used for display.
  3. preg_replace('/\s+/', ' ', $subject) turns every run of whitespace, line breaks included, into one space. The injected text becomes harmless words inside the subject instead of a new header.
  4. The final preg_match('/[\r\n]/', $clean) check confirms that no line break is left. Run a check like this on every value that goes into a header.

Example 3 — Accepted for delivery is not delivered

Wrap the send step in a function that takes the sender as a parameter. Here two small stand-ins replace mail() so the result is predictable. In production you would pass 'mail' instead.

PHP
<?php
function sendReport(callable $sender, string $to, string $subject): string
{
    $accepted = $sender($to, $subject);

    return $accepted
        ? "$to: accepted for delivery (not proof it arrived)"
        : "$to: rejected by the mail system";
}

// Stand-ins for mail(): one accepts any address with an @, one always fails.
$acceptsAtSign = fn (string $to, string $subject): bool => str_contains($to, '@');
$alwaysFails   = fn (string $to, string $subject): bool => false;

echo sendReport($acceptsAtSign, '[email protected]', 'Order 1042 shipped'), PHP_EOL;
echo sendReport($acceptsAtSign, 'not-an-email', 'Order 1042 shipped'), PHP_EOL;
echo sendReport($alwaysFails, '[email protected]', 'Order 1042 shipped'), PHP_EOL;

echo 'Next step: check the mail log or your SMTP provider for the real result.', PHP_EOL;
// With the real function: sendReport('mail', $to, $subject);
?>
mail() Tutorial

How It Works

  1. callable $sender accepts any function. A function name such as 'mail' works the same way as the arrow functions used here, which makes the sending step easy to test.
  2. The first stand-in returns true for any address that contains @, just as mail() returns true when the mail system takes the message. The text says "accepted", never "delivered".
  3. A false result, from the second and third calls, is the only case where you know the hand-off failed. Log it or show an error to the user.
  4. Even a true result can end in a bounce or a spam folder later. The mail.log setting, the server's mail log, and your SMTP provider's dashboard show what happened after the hand-off.

Next: PHP Mail Functions Index

After you know headers, the meaning of true, the php.ini settings, and header injection, open the functions index for both guides.

Start withWhy
mail()Send an email message with headers and check whether it was accepted
ezmlm_hash()Get the EZMLM list hash of an email address on old PHP versions

Full list: PHP Mail Functions index (/php/mail/function).

Frequently Asked Questions

Call mail($to, $subject, $message, $headers). It hands the message to the mail system that php.ini points to and returns true if the message was accepted for delivery. For production email with attachments, HTML templates, or SMTP login, most projects use a library such as PHPMailer or Symfony Mailer instead.
A return value of true only means PHP passed the message to the local mail system, such as sendmail or an SMTP server. It does not mean the message reached the inbox. The message can still be rejected later, land in spam, or bounce. Check the mail log and the bounce address to learn what really happened.
Pass them as the fourth argument. Since PHP 7.2 you can use an array such as ['From' => 'CodeToFun <[email protected]>', 'Reply-To' => '[email protected]']. Older code uses one string with each header separated by a carriage return and line feed. Use a From address on a domain you control, or many servers will mark the message as spam.
On Linux and macOS, set sendmail_path to the sendmail-compatible program, for example /usr/sbin/sendmail -t -i. On Windows, set SMTP, smtp_port, and sendmail_from so PHP can talk to an SMTP server directly. Restart the web server or PHP-FPM after you change php.ini.
It happens when user input that contains carriage return or line feed characters is placed into a header such as To, Subject, From, or Reply-To. The extra line lets an attacker add headers like Bcc and turn your form into a spam relay. Validate addresses with filter_var() and FILTER_VALIDATE_EMAIL, and strip or reject line breaks in every value that goes into a header.
Only when you work with an EZMLM mailing list, where the subscriber files are named after a hash of the address. ezmlm_hash() returns that hash for an email address. It was removed in PHP 8.0, so it is not available on current PHP versions, and most sites never need it.

Browse every Mail function

Open the functions index for guides with examples and FAQs.

Mail Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful