PHP – Sending Emails using PHP

The PHP mail() function is a simple way to send emails directly from your PHP script. To use the mail() function, you need to have a properly configured mail server on your hosting environment.

Here’s the basic syntax for the mail() function:

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )
  • $to: The recipient’s email address.
  • $subject: The subject of the email.
  • $message: The content of the email.
  • $additional_headers (optional): Additional headers for the email, such as “From,” “Cc,” “Bcc,” and “Reply-To.”
  • $additional_parameters (optional): Additional parameters that can be passed to the mail server (less commonly used).

Here’s an example of how to use the mail() function to send a simple email:

<?php
$to = "recipient@example.com";
$subject = "Test Email";
$message = "Hello! This is a test email sent using the PHP mail() function.";
$headers = "From: sender@example.com\r\n";
// Send the email using the mail() function
if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully!";
} else {
    echo "Email sending failed.";
}
?>

In this example, we’ve set the recipient’s email address, the subject, and the message content. We’ve also added a “From” header to specify the sender’s email address. Finally, we call the mail() function and check if it returns true (successful) or false (failed).

Keep in mind that the mail() function is quite basic and may not be suitable for sending complex or large volumes of emails. For more advanced use cases, consider using a library like PHPMailer or SwiftMailer, or using an email service like SendGrid, Mailgun, or Amazon SES.