What are best practices for setting up SMTP transport and authentication when sending emails using PHP?

When sending emails using PHP, it is important to properly configure the SMTP transport and authentication to ensure successful delivery. This involves setting up the SMTP server address, port, username, password, and encryption method. By following best practices for SMTP configuration, you can avoid common issues such as emails being marked as spam or not being delivered at all.

// Define SMTP server settings
$smtpServer = 'smtp.example.com';
$smtpPort = 587;
$smtpUsername = 'your_username';
$smtpPassword = 'your_password';
$smtpEncryption = 'tls';

// Create a new PHPMailer instance
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

// Configure SMTP settings
$mail->isSMTP();
$mail->Host = $smtpServer;
$mail->Port = $smtpPort;
$mail->SMTPAuth = true;
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
$mail->SMTPSecure = $smtpEncryption;
$mail->SMTPDebug = SMTP::DEBUG_OFF; // Disable debugging for production

// Send email
$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';

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