How can PHP be configured to authenticate with an SMTP server for mail sending without enabling relaying or SMTP without authentication?

To authenticate with an SMTP server for mail sending in PHP without enabling relaying or SMTP without authentication, you can use the PHPMailer library. PHPMailer allows you to set SMTP authentication credentials such as username and password to authenticate with the SMTP server.

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

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

// 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 and recipient
$mail->setFrom('from@example.com', 'Sender Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Subject';
$mail->Body = 'Email body content';

// Send the email
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}