← Back to Chapters

PHP – How to Send Email

? PHP – How to Send Email

? Quick Overview

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.

? Key Concepts

  • PHP mail sending depends on server configuration
  • mail() is suitable for basic use cases
  • SMTP libraries improve deliverability

? Syntax / Theory

The general syntax of the PHP mail function:

? View Code Example
// General syntax of PHP mail function
mail(to, subject, message, headers, parameters)

? Code Example(s)

Below is an example of sending a simple email using PHP:

? View Code Example
// 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.";
}
?>

? Live Output / Explanation

If the email is successfully sent, the message Email sent successfully! is displayed. Otherwise, a failure message appears.

? Interactive / Visual Concept

? PHP → Mail Server → Recipient Inbox

This flow shows how PHP passes the email to the server, which then delivers it to the recipient.

? Use Cases

  • Contact forms
  • Password reset emails
  • Account verification
  • Notification systems

✅ Tips & Best Practices

  • Always set a valid From header
  • Use SMTP libraries for production systems
  • Configure server mail settings properly

? Try It Yourself

  • Add CC and BCC headers
  • Send HTML formatted emails
  • Configure SMTP using a library like PHPMailer
  • Experiment with attachments