What alternative methods can be used to authenticate and send emails via SMTP in PHP, apart from ini_set?

When sending emails via SMTP in PHP, an alternative method to authenticate and send emails is by using the PHPMailer library. PHPMailer provides a more robust and flexible solution for sending emails with SMTP authentication. This library allows for easy configuration of SMTP settings, authentication methods, and email content.

// Include the PHPMailer library
require 'path/to/PHPMailer/PHPMailerAutoload.php';

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

// Set SMTP 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;

// Set email content
$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 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}