Send Email with PHP mail() Function
This guide provides a straightforward tutorial on how to send a basic
email using PHP’s native mail() function. You will learn
the basic syntax, understand the required parameters, and view a
practical, ready-to-use code example to implement email functionality in
your web applications.
The PHP mail() function allows you to send emails
directly from a script. Here is the basic syntax of the function:
mail(string $to, string $subject, string $message, array|string $additional_headers = "", string $additional_params = ""): boolKey Parameters
- $to: The receiver’s email address (e.g.,
recipient@example.com). - $subject: The subject of the email. This cannot contain any newline characters.
- $message: The body of the email. Each line should be separated with a LF () and lines should not exceed 70 characters.
- $additional_headers (Optional): String or array inserted at the end of the email header. This is typically used to specify the “From” address, “Reply-To” address, and email format (such as HTML).
Practical Code Example
Here is a complete, basic PHP script to send a plain-text email:
<?php
// Define recipient and email details
$to = "recipient@example.com";
$subject = "Test Email from PHP";
$message = "Hello!\n\nThis is a test email sent using the basic PHP mail() function.";
// Define headers
$headers = "From: sender@example.com\r\n" .
"Reply-To: sender@example.com\r\n" .
"X-Mailer: PHP/" . phpversion();
// Send the email
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully.";
} else {
echo "Email delivery failed.";
}
?>Important Requirements and Best Practices
- Server Configuration: For the
mail()function to work, your web server must have a local mail transfer agent (like Sendmail or Postfix) configured in thephp.inifile. If you are running PHP on a local machine (like XAMPP or MAMP), you will need to configure an SMTP server to send emails. - Email Deliverability: Emails sent via the basic
native
mail()function are often flagged as spam by modern email providers (such as Gmail or Outlook). To prevent this, ensure your “From” header uses a real domain hosted on your server, or use a robust library like PHPMailer combined with an external SMTP service for production environments.