The mail() function is built into PHP and is used to send emails directly from a web server. It’s a simple way to send notifications, contact form messages, order confirmations, and other types of messages.
Suitable for basic email functionality without using external libraries.
When you call the mail() function, PHP passes the email to the system’s mail transfer agent (MTA) installed on the server (typically Sendmail or Postfix). The MTA then processes and delivers the message to the specified address.
mail(to, subject, message, headers, parameters);
Parameter | Description |
---|---|
$to | Recipient’s email address. You can specify multiple addresses separated by commas. |
$subject | Subject of the email. Must not contain line breaks. |
$message | Main body of the message. |
$headers | Additional headers like From, Reply-To, Cc, Bcc, etc. |
$parameters | Extra parameters, such as specifying the sender for Sendmail (-f). |
<?php
$to = "user@example.com";
$subject = "Test Email";
$message = "Hello! This is a test email sent using PHP.";
$headers = "From: webmaster@yourdomain.com";
mail($to, $subject, $message, $headers);
?>
If you don’t specify a From: header, most mail servers will reject the message as suspicious or spam.
$headers = "From: noreply@yourdomain.com";
Use \r\n to separate lines in your message:
$message = "Hello,\r\n\r\nThank you for your order.\r\n\r\nBest regards,\r\nYour Team";
Use \r\n to separate multiple headers like Reply-To, Cc, and Bcc:
$headers = "From: admin@yourdomain.com\r\n";
$headers .= "Reply-To: support@yourdomain.com\r\n";
$headers .= "Cc: someone@yourdomain.com\r\n";
The mail() function doesn’t support attachments natively. But you can send HTML emails or set the content type manually:
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: info@yourdomain.com";
$message = "<h1>Hello!</h1><p>Your order has been received.</p>";
mail("user@example.com", "Order Confirmation", $message, $headers);
Problem | Cause / Solution |
---|---|
Email not delivered | Missing From: header or server IP is on a blacklist |
Email doesn’t send at all | No MTA installed (e.g. Sendmail/Postfix required) |
Error: mail() has been disabled | mail() is disabled in php.ini (often by host policy) |
Russian text appears as ???? | Charset not set to UTF-8 in headers |
Emails go to spam | Incorrect From, no SPF/DKIM, or misconfigured domain |
The mail() function is a basic but powerful tool for sending emails directly from PHP scripts. It is:
However, keep in mind its limitations:
If you plan to send emails regularly, make sure your server is properly configured for outgoing mail (with Sendmail/Postfix installed, SPF/DKIM records set up, and mail() enabled in php.ini).