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 = ""): bool

Key Parameters

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