W3docs

mail()

Today, we will discuss the mail() function in PHP. This function is used to send email messages from a PHP script.

Today, we will discuss the mail() function in PHP. This function is used to send email messages from a PHP script.

What is the mail() Function?

The mail() function is a built-in PHP function that sends email messages directly from a script. It relies on the local mail transfer agent (MTA) or SMTP settings configured in php.ini, which means it often requires server configuration to work correctly in development environments. The function requires a few parameters to be set, including the recipient email address, the subject of the email, and the message itself.

How to Use the mail() Function

Using the mail() function in PHP is relatively straightforward. Here is an example of how to use the function:

<?php
$to = '[email protected]';
$subject = 'Test email';
$message = 'This is a test email from PHP';

// Additional headers
$headers = 'From: [email protected]' . "\r\n" . 'Reply-To: [email protected]' . "\r\n" . 'X-Mailer: PHP/' . phpversion();

// Send the email and check the result
if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully.";
} else {
    echo "Email delivery failed.";
}
?>

In this example, we define the recipient, subject, and message as variables, then construct the headers. The mail() function returns a boolean indicating success or failure, so it's best practice to check the return value. Note that header injection is a security risk if any part of the headers comes from user input; always validate and sanitize external data. For production applications, consider using dedicated libraries like PHPMailer or Symfony Mailer, which handle encoding, authentication, and delivery reliability more robustly.

Conclusion

The mail() function provides a straightforward way to send emails directly from PHP. While it covers the basics of recipients, subjects, and headers, remember that it depends on your server's mail configuration. For complex workflows or production environments, dedicated email libraries are recommended. We hope this guide helps you integrate basic email functionality into your PHP projects.

Practice

Practice

What is correct about the PHP mail() function according to the content of the provided URL?