What are the limitations of the PHP mail function when it comes to sending emails over an SMTP server?

The limitations of the PHP mail function when sending emails over an SMTP server include limited support for authentication methods, lack of error handling, and potential issues with email deliverability. To overcome these limitations, it is recommended to use a dedicated email library like PHPMailer or Swift Mailer, which provide more robust features and better support for sending emails via SMTP.

// Example using PHPMailer library to send emails over SMTP

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // Include PHPMailer library

// Create a new PHPMailer instance
$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your_smtp_username';
    $mail->Password = 'your_smtp_password';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    // Recipient
    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    // Content
    $mail->isHTML(true);
    $mail->Subject = 'Subject';
    $mail->Body = 'Email content';

    // Send the email
    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}