What are the best practices for sending emails with PHP using Mailer classes?

When sending emails with PHP using Mailer classes, it is important to follow best practices to ensure successful delivery and avoid being marked as spam. Some key practices include setting proper headers, using a reliable SMTP server, avoiding sending mass emails in one go, and providing a clear unsubscribe option for recipients.

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

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

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

// Set up SMTP
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$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 = 'This is the 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';
}
?>