Skip to content

PHP Mail

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. It requires parameters for the recipient address, subject, and message body.

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:

How to Use the mail() Function in PHP?

php
<?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 for success
if (mail($to, $subject, $message, $headers)) {
    echo 'Email sent successfully.';
} else {
    echo 'Failed to send email.';
}
?>

In this example, we set the recipient email address, the subject of the email, and the message itself as variables. We also set additional headers for the email, such as the sender's email address and the X-Mailer header. Finally, we call the mail() function with these parameters to send the email.

Note: The mail() function relies on the server's local mail transfer agent (MTA). On many modern hosting environments, it may fail or deliver to spam without proper configuration. For production applications, consider using established libraries like PHPMailer or Symfony Mailer, which handle authentication, encoding, and deliverability. Additionally, ensure your domain has valid SPF, DKIM, and DMARC records to improve inbox placement.

Conclusion

The mail() function in PHP provides a simple way to send email messages from a script. By using this function, you can send emails to recipients, set the subject and content, and add additional headers for customization. We hope that this guide has been helpful in understanding how to use the mail() function in your PHP code.

Practice

What are the parameters of the PHP mail() function?

Dual-run preview — compare with live Symfony routes.