Send email
Mail leaves a PHP program through a local transport, and the function that hands a message to it is mail(). The examples below were run here: this machine has the sendmail binary but no mail server behind it, so the two sending calls return false, and the page says why.
mail() sketch
Function mail hands a message to the local mail system. Pass the recipient, the subject, and a plain text body.
It returns true when the message was accepted for delivery. Acceptance is not a proof that the inbox received it.
<?php var_dump(mail("user@example.com", "Hello", "Welcome aboard"));
php mail.php
The run of this block prints bool(false) and the warning mail(): Sendmail exited with non-zero exit code 1, because the sendmail binary here has no SMTP host to talk to. The warning line names the temporary file of the run, so the page keeps the result in prose instead of an output block. A machine with a working transport answers true instead, and the code around the call does not change.
Headers
Headers set the sender, the reply address, and the content type. Build them as one string with carriage return plus line feed between lines.
Never copy user input into headers without strict validation. A newline inside input can inject extra headers.
<?php $headers = "From: hello@example.com\r\nContent-Type: text/plain; charset=UTF-8"; var_dump(mail("user@example.com", "Hello", "Body text", $headers)); var_dump(substr_count($headers, "\r\n") + 1);
php headers.php
The sending call fails for the same reason as above, and the second statement of the block prints int(2) for the two header lines the string carries. That count is the reason a newline in a user value is dangerous: it can add a whole header of its own.
HTML parts note
HTML mail needs a matching content type and escaped dynamic values. Keep the layout simple so many clients render it the same way.
Escape names and links before they enter the HTML body. Plain text remains the safest default for system messages.
<?php $name = "Ada <b>Lovelace</b>"; $body = "<p>Hello " . htmlspecialchars($name, ENT_QUOTES, "UTF-8") . "</p>"; echo $body, PHP_EOL;
php body.php
<p>Hello Ada <b>Lovelace</b></p>
The name keeps its characters, and the angle brackets of the markup that arrived with it become entities, so the message body has one real tag and no second one.
Queue, do not block
Sending mail can take seconds, so web requests should only queue the job. A background worker sends the queued messages later.
Append the job to a queue file or table during the request. Return a fast response and let the worker handle retries.
<?php $job = "user@example.com|Hello"; file_put_contents(__DIR__ . "/queue.txt", $job . "\n", FILE_APPEND); echo "queued", PHP_EOL; echo trim(file_get_contents(__DIR__ . "/queue.txt")), PHP_EOL;
php queue.php
queued
user@example.com|Hello
The request ends after one append, and the line in the file is the whole job. A worker that reads the file later is the part that waits for the mail server.
Exercises
- Add a Reply-To header to the headers example and count the lines again.
- Put a user name with a newline into the headers string and describe the extra header it creates.
- Escape a link in the HTML body and check the entities in the output.
- Append two jobs to the queue file and print the file with file().
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
mail()need besides a correct call?Answer
A local mail transport that can deliver the message
The function hands the message to a transport, and without one it returns false, as the run on this page shows.
-
Why is a newline in a user value dangerous inside a header string?
Answer
It can start an extra header, such as a blind copy
Headers are separated by line breaks, so a value that carries one adds a header the sender never wrote.
-
Which content type suits a message with plain text only?
Answer
text/plain; charset=UTF-8Plain text needs no markup and every client renders it the same way.
-
Why does a web request only queue a mail job?
Answer
Because the mail server can take seconds, and the visitor should not wait
A worker sends later and retries on failure, while the request answers at once.
-
What does this program print?
<?php $headers = "From: hello@example.com\r\nContent-Type: text/plain; charset=UTF-8"; echo substr_count($headers, "\r\n") + 1;Answer
2
One line break separates the two headers, and the first header has no break before it.
-
What does this program print?
<?php $name = "Ada\r\nBcc: evil@example.com"; var_dump(str_contains($name, "\r\n"));Answer
bool(true)
The escape sequence is a real carriage return and line feed in the string, so the test finds it.
-
What does this program print?
<?php $body = "<p>Hello</p>"; echo htmlspecialchars($body, ENT_QUOTES, "UTF-8");Answer
<p>Hello</p>
The escape turns both tags into entities, so the text arrives as text.
-
What does this program print, run in an empty folder?
<?php $job = "user@example.com|Hello"; file_put_contents(__DIR__ . "/queue.txt", $job . "\n", FILE_APPEND); file_put_contents(__DIR__ . "/queue.txt", $job . "\n", FILE_APPEND); echo count(file(__DIR__ . "/queue.txt"));Answer
2
Each append writes one line, and
file()returns one element per line. -
A queue worker reads the file while a request appends to it. What is the simple guard?
Answer
Open the file with
FILE_APPEND | LOCK_EXThe exclusive lock keeps a half written line from being read as a job.
-
Which value must never go into a header without validation?
Answer
A value from the form, such as the sender name
Anything a visitor types can carry a line break or an address, so it needs a strict check or a header library.
The examples call mail(), htmlspecialchars(), file_put_contents() and substr_count(). The programs on this page were run with PHP 8.5.13 (php -v) with the commands shown above.
Article author: Arthur Isaev