PHP's built-in mail() hands a message to whatever mail program the server is configured with, and returns true as soon as that program accepts it. It does not authenticate to a remote SMTP server, gives you no delivery feedback, and is a frequent source of "sent but never arrived" bugs. For reliable sending, use PHPMailer (or a similar library) with SMTP authentication over TLS to a mail service, and authenticate your sending domain.
This guide explains how mail() works and where it falls short, then shows complete PHPMailer examples for STARTTLS on port 587 and implicit TLS on port 465, HTML bodies, attachments, error handling and debugging. For a framework-level approach, see the PHPMailer SMTP guide and, if you use Laravel, Laravel mail configuration.
How the mail() function works
On Linux and macOS, mail() pipes the message to the program named by the sendmail_path setting in php.ini, commonly sendmail, Postfix's sendmail wrapper or msmtp. On Windows it historically used the SMTP and smtp_port settings to talk to a server directly, without authentication or TLS support. Either way PHP builds nothing smart for you: you supply the headers as a string or array and any formatting mistakes are yours.
<?php
$to = "[email protected]";
$subject = "Order confirmation";
$message = "Thanks for your order.";
$headers = [
"From" => "Shop <[email protected]>",
"Reply-To" => "[email protected]",
"MIME-Version" => "1.0",
"Content-Type" => "text/plain; charset=UTF-8",
];
// Array headers are supported since PHP 7.2
$ok = mail($to, $subject, $message, $headers);
var_dump($ok);A true result only says the handoff worked. If the local MTA is missing, misconfigured or blocked from the internet, the message sits in a queue or bounces to a mailbox nobody reads.
Why mail() fails or lands in spam
- No SMTP authentication. The message leaves from your web server's IP address, which is often a shared or residential-style address with no reputation for mail and may be on blocklists. Many hosts also block outbound port 25.
- No domain alignment. Without SPF that includes the server and a DKIM signature for your domain, receivers have nothing to trust. See authenticating your sending domain.
- Poor or missing reverse DNS and HELO. The server's identity does not match its address; see reverse DNS and HELO.
- Weak diagnostics. No SMTP transcript, no response codes, no per-recipient result.
- Header injection risk. Putting user input into headers or the To field without validation lets attackers add recipients and send spam through your site. See header injection.
- No encryption control. You cannot require TLS to the next hop from PHP.
mail() versus PHPMailer with SMTP
| Aspect | mail() | PHPMailer with SMTP |
|---|---|---|
| Transport | Local MTA or unauthenticated server | Direct authenticated connection to the mail service |
| TLS | Depends on server config | STARTTLS or implicit TLS, verified by default |
| Authentication | None from PHP | Username and password, or OAuth2 where supported |
| HTML and attachments | You build MIME by hand | addAttachment(), isHTML(), embedded images |
| Errors | Boolean only | Exceptions with the server reply and optional debug output |
| Character encoding | Manual | Handled with CharSet and Encoding settings |
| Injection protection | Your responsibility | Rejects line breaks in headers and validates addresses |
| Best for | Local development or tightly managed servers | Production applications |
Install PHPMailer and send with SMTP
composer require phpmailer/phpmailer<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require __DIR__ . "/vendor/autoload.php";
$mail = new PHPMailer(true); // true enables exceptions
try {
$mail->isSMTP();
$mail->Host = getenv("SMTP_HOST");
$mail->SMTPAuth = true;
$mail->Username = getenv("SMTP_USER");
$mail->Password = getenv("SMTP_PASS");
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // port 587
$mail->Port = 587;
$mail->Timeout = 30;
$mail->CharSet = "UTF-8";
$mail->setFrom("[email protected]", "Example Shop");
$mail->addAddress("[email protected]", "A. User");
$mail->addReplyTo("[email protected]", "Support");
$mail->isHTML(true);
$mail->Subject = "Your order is confirmed";
$mail->Body = "<h1>Thank you</h1><p>Your order <strong>#1001</strong> is confirmed.</p>";
$mail->AltBody = "Thank you. Your order #1001 is confirmed.";
$mail->addAttachment("/var/app/invoices/1001.pdf", "invoice-1001.pdf");
$mail->send();
echo "Sent";
} catch (Exception $e) {
error_log("Mail error: " . $mail->ErrorInfo);
echo "Message could not be sent.";
}For implicit TLS on port 465, set $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; and $mail->Port = 465;. Load credentials from the environment or a configuration file outside the web root; never put them in templates or version control. Always set AltBody so the message has a plain-text part, and keep SMTPAutoTLS at its default so a server that offers STARTTLS is used. Do not set SMTPOptions to disable certificate verification to silence an error; fix the certificate or host name instead. Port and TLS background is in SMTP settings, ports and authentication.
Debug the SMTP conversation
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // client and server messages
$mail->Debugoutput = function ($str, $level) {
error_log("SMTP debug: " . $str);
};Debug output shows the banner, extensions, TLS negotiation, authentication and the final reply. Turn it off in production, and strip credentials before sharing a log; AUTH lines are only base64 encoded. If you need to test the server outside PHP, use the commands in testing an SMTP connection.
Sending to many recipients safely
- Send one message per recipient with personalised content, or use Bcc sparingly for small internal groups. A shared To list exposes addresses.
- Reuse one connection with
$mail->SMTPKeepAlive = trueand callclearAddresses()andclearAttachments()between messages. - Respect your provider's rate limits and run bulk jobs from a CLI worker or queue, not from a web request.
- Validate addresses with
filter_var($email, FILTER_VALIDATE_EMAIL)before adding them, and stop sending to addresses that hard bounce. - Include unsubscribe handling for marketing mail; see one-click unsubscribe setup.
A safe contact-form pattern
<?php
$name = trim($_POST["name"] ?? "");
$email = filter_var($_POST["email"] ?? "", FILTER_VALIDATE_EMAIL);
$text = trim($_POST["message"] ?? "");
if ($name === "" || !$email || $text === "") {
http_response_code(422);
exit("Please complete all fields.");
}
// The From address is fixed to your own authenticated domain.
// The visitor's address goes in Reply-To, never in From.
$mail->setFrom("[email protected]", "Website form");
$mail->addAddress("[email protected]");
$mail->addReplyTo($email, $name);
$mail->Subject = "New message from the website";
$mail->Body = "Name: " . $name . "
Email: " . $email . "
" . $text;
$mail->send();The two rules in this snippet prevent most abuse and most deliverability trouble. First, the visitor's address never becomes the From address: a message claiming to come from a domain you do not control fails DMARC at strict receivers and looks like spoofing. Put the visitor in Reply-To so your team can still answer with one click. Second, the form accepts only validated values and sends to a fixed recipient, so it cannot be turned into an open mail gateway. Add a rate limit and a bot check (a honeypot field, CAPTCHA or a signed token) for public forms, and log the sender IP for abuse investigation. More on defending forms is in signup bot protection.
Character sets, line endings and plain text
With mail() you must set the MIME headers, encode non-ASCII subjects yourself (for example with mb_encode_mimeheader()) and take care with line endings: headers are separated by CRLF, and a bare newline in a header can corrupt the message or open a path to injection. PHPMailer handles all of this when you set CharSet to UTF-8 and use its setters. It also limits line length and chooses a transfer encoding, which avoids a family of problems with long lines and 8-bit text that otherwise show up as unreadable or truncated mail. These details are the quiet reason many teams stop using mail() even when it technically works.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| mail() returns true but nothing arrives | Local MTA missing, queued, blocked or rejected later | Check the MTA log and the mail queue; move to SMTP |
| mail() returns false | sendmail_path wrong or no MTA installed | Check php.ini and phpinfo(); or use PHPMailer |
| SMTP Error: Could not authenticate | Wrong credentials or the account needs an app password | Verify with a test client. See error 535 |
| SMTP connect() failed | Port blocked, wrong host, or TLS mode mismatch | Match 587 with STARTTLS and 465 with SMTPS; test connectivity |
| Certificate verify failed | Host name does not match, outdated CA bundle | Use the exact host name; update the system CA bundle |
| Garbled characters | Missing CharSet | Set $mail->CharSet = "UTF-8" |
| Lands in spam | No SPF, DKIM or alignment; poor content | Authenticate the domain and send through a reputable service |
| Works locally, fails in production | Host blocks outbound SMTP | Use a permitted port or an HTTP email API |
When to use which
Use mail() only where the server has a properly configured, authenticated local MTA that you manage, such as a relay set up through Postfix. For everything else, including contact forms, order confirmations and password resets, use SMTP through PHPMailer or your framework's mailer. Many sites replace mail() globally by setting sendmail_path to a small relay client such as msmtp, so legacy code keeps working; see sending from the command line with msmtp. Sending from an application rather than a person also means you want bounce and complaint handling, which a bare mail() call cannot give you.
If you use MigoSMTP, set the host to smtp.migosmtp.com, use port 587 with STARTTLS or 465 with SMTPS, and authenticate your domain before going live.
Replace mail() with authenticated sending Relay your PHP application mail through MigoSMTP and get delivery events.
References and further reading
Frequently asked questions
Why does PHP mail() return true but the email never arrives?
Because true only means the local mail program accepted the message. Delivery can still fail later, or the message can be rejected or filtered as spam.
Is PHPMailer better than mail()?
For production, yes. It authenticates to an SMTP server over TLS, builds correct MIME for HTML and attachments, and reports errors with exceptions.
Which port and encryption should PHPMailer use?
Port 587 with PHPMailer::ENCRYPTION_STARTTLS, or port 465 with PHPMailer::ENCRYPTION_SMTPS. Avoid port 25 for application submission.
How do I send an attachment with PHPMailer?
Call $mail->addAttachment() with the file path and an optional file name before send().
How do I stop PHP contact forms being abused?
Validate addresses, never place user input in headers, fix the From address to your own domain, add rate limiting and bot protection, and use a library that rejects header injection.