What are the advantages of using SMTP authentication in PHP for sending emails through PHPMailer?

Using SMTP authentication in PHP for sending emails through PHPMailer adds an extra layer of security by requiring users to provide valid credentials before sending emails. This helps prevent unauthorized access and misuse of the email server. Additionally, SMTP authentication allows for more reliable delivery of emails as it verifies the sender's identity.

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

// Include PHPMailer library files
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.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->Port = 587; // Use 587 for TLS or 465 for SSL

// Set email content and recipient
$mail->setFrom('your_email@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 could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Email has been sent';
}