How to send an email using PHP?

Introduction:
PHP has a built-in mail() function to send emails. This function is simple to use but requires a properly configured mail server (e.g., Sendmail, Postfix).

Example:

<?php
$to = "example@example.com";
$subject = "Test Email";
$message = "This is a test email.";
$headers = "From: sender@example.com";

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully!";
} else {
    echo "Failed to send email.";
}
?>

Explanation:

  • $to specifies the recipient’s email address.
  • $subject is the subject line of the email.
  • $message contains the email body.
  • $headers is optional but often used to specify the sender’s email address.
  • The mail() function returns true if the email is sent successfully, otherwise false.

Leave a Reply

Your email address will not be published. Required fields are marked *