PHP provides built-in functions for sending emails. The most common way is using the mail() function. While simple, real-world applications usually rely on SMTP servers or libraries like PHPMailer for reliability.
The general syntax of the PHP mail function:
// General syntax of PHP mail function
mail(to, subject, message, headers, parameters)
Below is an example of sending a simple email using PHP:
// Send a basic email using PHP mail()
<?php
$to = "recipient@example.com";
$subject = "Test Email from PHP";
$message = "Hello, this is a test email sent using the PHP mail() function.";
$headers = "From: sender@example.com";
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully!";
} else {
echo "Failed to send email.";
}
?>
If the email is successfully sent, the message Email sent successfully! is displayed. Otherwise, a failure message appears.
? PHP → Mail Server → Recipient Inbox
This flow shows how PHP passes the email to the server, which then delivers it to the recipient.