What are some best practices for setting up SMTP authentication and handling email addresses correctly when using PHPMailer?

When setting up SMTP authentication with PHPMailer, it is important to ensure that you are providing the correct credentials for the SMTP server. Additionally, handling email addresses correctly involves validating input to prevent injection attacks and ensuring that the email addresses are properly formatted before sending emails.

// Set up PHPMailer with SMTP authentication
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

$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;

// Validate and sanitize email addresses before sending
$to = filter_var($_POST['to_email'], FILTER_VALIDATE_EMAIL);
$from = filter_var($_POST['from_email'], FILTER_VALIDATE_EMAIL);

$mail->setFrom($from, 'Your Name');
$mail->addAddress($to);

$mail->Subject = 'Subject';
$mail->Body = 'Email body content';

if($mail->send()){
    echo 'Email sent successfully';
} else {
    echo 'Email could not be sent';
}