New guide: how to warm up a dedicated IP without hurting your reputation. Read now →
Log in
MigoSMTP
SMTP and APIUpdated 4 Nov 2026

PHP mail() versus PHPMailer with SMTP: how to send email from PHP reliably

Why PHP mail() often fails or lands in spam, how it differs from authenticated SMTP, and how to send HTML, attachments and bulk-safe mail with PHPMailer over STARTTLS or SSL, with working code and troubleshooting.

SQ
Written by Sana Qureshi
Email Compliance Specialist
Reviewed by Kenji Watanabe
  • Published10 Jun 2024
  • Read time8 min
  • Length1,590 words
Share this guide

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.

mail()Passes the message to a local MTA via sendmail_path (or an SMTP server on Windows); no per-message delivery result
PHPMailer + SMTPAuthenticated, encrypted submission to a mail service; clear exceptions and debug output
Return valuetrue from mail() means the local program took the message, not that it was delivered
RuleUse SMTP with TLS and a domain you have authenticated

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

Aspectmail()PHPMailer with SMTP
TransportLocal MTA or unauthenticated serverDirect authenticated connection to the mail service
TLSDepends on server configSTARTTLS or implicit TLS, verified by default
AuthenticationNone from PHPUsername and password, or OAuth2 where supported
HTML and attachmentsYou build MIME by handaddAttachment(), isHTML(), embedded images
ErrorsBoolean onlyExceptions with the server reply and optional debug output
Character encodingManualHandled with CharSet and Encoding settings
Injection protectionYour responsibilityRejects line breaks in headers and validates addresses
Best forLocal development or tightly managed serversProduction 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 = true and call clearAddresses() and clearAttachments() 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

SymptomLikely causeFix
mail() returns true but nothing arrivesLocal MTA missing, queued, blocked or rejected laterCheck the MTA log and the mail queue; move to SMTP
mail() returns falsesendmail_path wrong or no MTA installedCheck php.ini and phpinfo(); or use PHPMailer
SMTP Error: Could not authenticateWrong credentials or the account needs an app passwordVerify with a test client. See error 535
SMTP connect() failedPort blocked, wrong host, or TLS mode mismatchMatch 587 with STARTTLS and 465 with SMTPS; test connectivity
Certificate verify failedHost name does not match, outdated CA bundleUse the exact host name; update the system CA bundle
Garbled charactersMissing CharSetSet $mail->CharSet = "UTF-8"
Lands in spamNo SPF, DKIM or alignment; poor contentAuthenticate the domain and send through a reputable service
Works locally, fails in productionHost blocks outbound SMTPUse 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.

Explore the SMTP relay

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.

Topics#php#phpmailer#mail function#smtp#tls
Was this guide helpful?Your answer helps us improve our documentation.

Start sending in minutes.

Create an account, add your domain and send your first email.

Get started Talk to sales