How to Use mail() Function in PHP: Syntax and Examples
Use the
mail() function in PHP to send emails by specifying the recipient, subject, message, and optional headers. The basic syntax is mail(to, subject, message, headers), where to is the email address of the recipient.Syntax
The mail() function in PHP sends an email with the following parameters:
- to: The recipient's email address.
- subject: The email subject line.
- message: The body of the email.
- headers (optional): Additional headers like
From,Reply-To, etc. - parameters (optional): Additional command line parameters for the mail program.
Only the first three parameters are required.
php
bool mail(string $to, string $subject, string $message, string $headers = null, string $parameters = null)
Example
This example shows how to send a simple email with a subject and message to a recipient. It also sets a From header to specify the sender's email.
php
<?php $to = 'friend@example.com'; $subject = 'Hello from PHP'; $message = "Hi there,\nThis is a test email sent using PHP's mail function."; $headers = 'From: sender@example.com' . "\r\n" . 'Reply-To: sender@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); if (mail($to, $subject, $message, $headers)) { echo 'Email sent successfully.'; } else { echo 'Email sending failed.'; } ?>
Output
Email sent successfully.
Common Pitfalls
Common mistakes when using mail() include:
- Not setting the
Fromheader, which can cause emails to be rejected or marked as spam. - Incorrect line endings in headers; use
\r\nfor compatibility. - Assuming
mail()always works; it depends on server configuration and may fail silently. - Not validating email addresses before sending.
Always check the return value of mail() to know if PHP successfully handed the email to the mail server.
php
<?php // Wrong: Missing From header mail('friend@example.com', 'No From Header', 'Message'); // Right: With From header $headers = 'From: sender@example.com' . "\r\n"; mail('friend@example.com', 'With From Header', 'Message', $headers); ?>
Quick Reference
| Parameter | Description | Required |
|---|---|---|
| to | Recipient email address | Yes |
| subject | Email subject line | Yes |
| message | Email body content | Yes |
| headers | Additional headers like From, Reply-To | No |
| parameters | Extra command line parameters for mail program | No |
Key Takeaways
Use mail(to, subject, message, headers) to send emails in PHP.
Always include a From header to avoid spam filters.
Check the mail() function's return value to confirm sending success.
Use \r\n for line breaks in headers for compatibility.
mail() depends on server setup; it may not work on all hosts without configuration.