How to send email using php mail function

The classic PHP mail() function!

To send an email using the PHP mail() function, you'll need to provide the following information:

  1. To: The recipient's email address.
  2. Subject: The subject line of the email.
  3. Body: The email body content.
  4. From: The sender's email address.
  5. Headers: Optional headers, such as From, Reply-To, and CC.

Here's a basic example of how to use the mail() function:

<?php
// Define the email variables
$to = '[email protected]';
$subject = 'Test Email';
$body = 'This is a test email sent using PHP mail() function.';
$from = '[email protected]';

// Define the headers
$headers = 'From: '. $from. "\r\n".
           'Reply-To: '. $from. "\r\n".
           'CC: '. '[email protected]'. "\r\n";

// Send the email
if (mail($to, $subject, $body, $headers)) {
    echo 'Email sent successfully!';
} else {
    echo 'Error sending email.';
}
?>

In this example:

Note that the mail() function is a simple, low-level function that doesn't provide any error handling or logging. If you need more advanced features, such as email validation, spam filtering, or logging, you may want to consider using a more robust email library or service.

Also, keep in mind that the mail() function is not secure, as it sends emails in plain text. If you need to send sensitive information, consider using a more secure method, such as using a library like PHPMailer or SwiftMailer.