What alternative methods or libraries can be used in PHP for sending emails more reliably than the mail() function?

The mail() function in PHP can be unreliable for sending emails as it relies on the server's configuration and can be affected by spam filters. To send emails more reliably, you can use alternative methods such as using a library like PHPMailer or Swift Mailer, which provide more features and better handling of email sending.

// Using PHPMailer library to send emails
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';

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

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

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

$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Subject of the email';
$mail->Body = 'Body of the email';

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