What are the limitations of using the mail() function in PHP for sending emails?

The limitations of using the mail() function in PHP for sending emails include potential issues with deliverability, lack of support for advanced email features like attachments and HTML formatting, and security vulnerabilities if not properly sanitized. To overcome these limitations, it is recommended to use a dedicated email library like PHPMailer or SwiftMailer, which provide more robust functionality and better support for modern email standards.

// Example using PHPMailer library to send an email with attachments and HTML formatting

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

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

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

// Set up SMTP configuration
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

// Set email content
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('to@example.com', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->isHTML(true);
$mail->Body = '<h1>Hello, this is a test email!</h1>';

// Add attachments
$mail->addAttachment('path/to/file.pdf');

// Send email
if ($mail->send()) {
    echo 'Email sent successfully';
} else {
    echo 'Error sending email: ' . $mail->ErrorInfo;
}