How can you send email in PHP?

The mail() function is used to send email in PHP.

bool mail($to,$subject,$message,$header);

To send an email in PHP, you can use the mail() function. Here’s a basic example:

php
$to = "recipient@example.com";
$subject = "Test email";
$message = "This is a test email sent from PHP.";
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: sender@example.com\r\n";
$headers .= "Content-type: text/html\r\n";

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

In this example:

  • $to is the recipient’s email address.
  • $subject is the subject of the email.
  • $message is the body of the email.
  • $headers contain additional headers such as “From”, “Reply-To”, and “Content-type”.

Please note that the mail() function relies on the system’s configured email settings, such as SMTP, to send emails. Make sure your server is properly configured to send emails. Additionally, the mail() function might not be available or might not work as expected on all server configurations. In such cases, using a library like PHPMailer or Swift Mailer might be a better option.