Definition and Usage
The PHP `mail()` function is a built-in function that allows you to send emails directly from a PHP script. It is commonly used in web applications to send automated emails, such as registration confirmations, password reset links, or contact form submissions. The function works by connecting to a local mail server (like Sendmail on Linux or SMTP on Windows) to deliver the email.
How Does It Work?
When you call the `mail()` function, PHP communicates with the mail server configured on your system. The server then processes the email & sends it to the recipient’s email address. This makes the `mail()` function a simple & effective way to handle email functionality in PHP.
Basic Requirements
Before using the `mail()` function, ensure that:
1. Your server has a mail transfer agent (MTA) like Sendmail or Postfix installed & configured.
2. PHP is properly configured to use the MTA. You can check this in your `php.ini` file under the `sendmail_path` directive.
Syntax
The syntax of the PHP `mail()` function is straightforward but requires careful attention to its parameters. Understanding the syntax is crucial to using the function effectively. The basic structure of the `mail()` function is:
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )
In this syntax:
1. `$to` (Required): This is the email address of the recipient. It can be a single email address or multiple addresses separated by commas.
2. `$subject` (Required): This is the subject line of the email. It should be a plain text string.
3. `$message` (Required): This is the body of the email. It can be plain text or HTML, depending on the headers you provide.
4. `$additional_headers` (Optional): This parameter allows you to add extra headers to the email, such as `From`, `Reply-To`, `CC`, `BCC`, & `Content-Type`. Headers must be separated by `\r\n`.
5. `$additional_parameters` (Optional): This is an advanced parameter used to pass additional flags to the mail server. It’s rarely used in most cases.
Parameter Values
The `mail()` function in PHP has five parameters, out of which three are required & two are optional. Understanding these parameters is essential to use the function effectively. Let’s understand each parameter in detail:
1. `$to` (Required)
This parameter specifies the recipient’s email address. It can be a single email address or multiple addresses separated by commas.
- Example: `"recipient@example.com"` or `"recipient1@example.com, recipient2@example.com"`.
2. `$subject` (Required)
This parameter defines the subject line of the email. It should be a plain text string.
- Example: `"Test Email from PHP"`.
3. `$message` (Required)
This parameter contains the body of the email. It can be plain text or HTML, depending on the headers you provide.
- Example: `"Hello, this is a test email sent using PHP's mail() function."`.
4. `$additional_headers` (Optional)
This parameter allows you to add extra headers to the email. Headers provide additional information, such as the sender’s email address, reply-to address, CC, BCC, & content type.
- Example:
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: no-reply@example.com\r\n";
$headers .= "CC: cc@example.com\r\n";
$headers .= "BCC: bcc@example.com\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
5. `$additional_parameters` (Optional)
This is an advanced parameter used to pass additional flags to the mail server. It’s rarely used in most cases.
- Example: `"-fsender@example.com"` (used to set the envelope sender address).
Complete Code Example
Now, take a look at a complete example showing the use of all parameters in the `mail()` function. This example contains optional headers & sends an HTML email.
<?php
// Define the recipient email address
$to = "recipient@example.com";
// Define the subject of the email
$subject = "Test HTML Email from PHP";
// Define the message body in HTML format
$message = "
<html>
<head>
<title>Test HTML Email</title>
</head>
<body>
<h1>Hello!</h1>
<p>This is a <strong>test email</strong> sent using PHP's <code>mail()</code> function.</p>
<p>It contains HTML content.</p>
</body>
</html>
";
// Define additional headers
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: no-reply@example.com\r\n";
$headers .= "CC: cc@example.com\r\n"; // Carbon copy
$headers .= "BCC: bcc@example.com\r\n"; // Blind carbon copy
$headers .= "Content-Type: text/html; charset=UTF-8\r\n"; // Set content type to HTML
// Send the email
if (mail($to, $subject, $message, $headers)) {
echo "HTML email sent successfully!";
} else {
echo "Failed to send email.";
}
?>
In this Code:
1. Recipient (`$to`): The email is sent to `recipient@example.com`.
2. Subject (`$subject`): The subject line is "Test HTML Email from PHP".
3. Message (`$message`): The email body is written in HTML format. It includes headings, paragraphs, & bold text.
4. Headers (`$headers`):
- `From`: Specifies the sender’s email address.
- `Reply-To`: Specifies the email address to which replies should be sent.
- `CC`: Adds a carbon copy recipient.
- `BCC`: Adds a blind carbon copy recipient (not visible to other recipients).
- `Content-Type`: Specifies the email format as HTML & sets the character encoding to UTF-8.
5. `mail()` Function: The function is called with all the required & optional parameters. It returns `true` if the email is sent successfully.
Testing the Code
Save this code in a `.php` file (e.g., `send_html_email.php`) & run it on a server with PHP installed. If everything is configured correctly, you should see the message "HTML email sent successfully!" & receive the email in the recipient’s inbox.
PHP Mail Example
Let’s start by sending a basic email using the mail() function in PHP. Here's an example:
Example: Sending a Simple Email
<?php
$to = "recipient@example.com"; // Recipient's email address
$subject = "Test Email from PHP"; // Subject of the email
$message = "Hello, this is a simple email sent from a PHP script!"; // Email body
// Sending the email
if(mail($to, $subject, $message)) {
echo "Email sent successfully!";
} else {
echo "Failed to send email.";
}
?>

You can also try this code with Online PHP Compiler
Run Code
Explanation:
- We define the recipient's email, the subject, and the message body.
- We use the mail() function to send the email and check if it was sent successfully using an if condition.
- If the email is sent, a success message is displayed; otherwise, a failure message is shown.
When you run this script, an email will be sent to the recipient with the subject and message you’ve defined.
PHP Mail: Send HTML Message
You can also send HTML-formatted emails using PHP. This is useful when you want your email to include elements like bold text, links, or images.
Example: Sending an HTML Email
<?php
$to = "recipient@example.com"; // Recipient's email address
$subject = "HTML Email from PHP"; // Subject of the email
// HTML Message
$message = "
<html>
<head>
<title>HTML Email</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is an <b>HTML</b> email sent from PHP!</p>
<p>Visit <a href='https://www.example.com'>this link</a>.</p>
</body>
</html>
";
// Set Content-Type header for HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: sender@example.com" . "\r\n"; // Sender's email address
// Sending the email
if(mail($to, $subject, $message, $headers)) {
echo "HTML email sent successfully!";
} else {
echo "Failed to send HTML email.";
}
?>

You can also try this code with Online PHP Compiler
Run Code
Explanation:
- The message is written in HTML format.
- We set the Content-type header to text/html to tell the email client that this is an HTML email.
- The mail() function is used to send the email with the correct headers to display the HTML content.
This script will send an HTML email with a heading, bold text, and a clickable link.
PHP Mail: Send Mail with Attachment
Sometimes, you may want to send emails with attachments like images, documents, or other files. To achieve this, you need to encode the file and add it to the email headers.
Example: Sending an Email with Attachment
<?php
$to = "recipient@example.com"; // Recipient's email address
$subject = "Email with Attachment"; // Subject of the email
$from = "sender@example.com"; // Sender's email address
// File to attach
$file = "example.pdf"; // Specify the file to attach
$fileContent = chunk_split(base64_encode(file_get_contents($file))); // Encode the file content
// Boundary string for separating email content and attachment
$boundary = md5(time());
// Set headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "From: $from" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"" . "\r\n";
// Email body
$message = "--$boundary\r\n";
$message .= "Content-Type: text/plain; charset=UTF-8\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$message .= "Hello, please find the attached file.\r\n\r\n";
// Attach file
$message .= "--$boundary\r\n";
$message .= "Content-Type: application/pdf; name=\"$file\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment; filename=\"$file\"\r\n\r\n";
$message .= $fileContent . "\r\n\r\n";
$message .= "--$boundary--";
// Send email
if(mail($to, $subject, $message, $headers)) {
echo "Email with attachment sent successfully!";
} else {
echo "Failed to send email with attachment.";
}
?>

You can also try this code with Online PHP Compiler
Run Code
Explanation:
- The attachment file is read and encoded using base64.
- We create a boundary string to separate the email’s content and the attachment.
- The email headers are set for MIME format, and the attachment is added within the email body.
When you run this code, the email will be sent with a file attached to it, ready for the recipient to download.
Frequently Asked Questions
Can I use the mail() function to send emails with attachments?
Yes, you can send emails with attachments by encoding the file and including it in the email’s body with the correct MIME headers.
How can I send HTML emails using PHP?
You can send HTML emails by setting the Content-Type header to text/html and writing the email body in HTML format.
Is the mail() function secure for sending sensitive data?
The mail() function itself does not include encryption for the email, so it’s recommended to use additional security measures like SMTP for sensitive data.
Conclusion
In this article, we have covered the essential aspects of the PHP mail() function. We learned how to send basic text emails, HTML emails, and even emails with attachments. The examples provided help you understand the different use cases of the mail() function and how it can be integrated into your PHP applications.