What best practices should be followed when retrieving email addresses from a database and sending newsletters in PHP?

When retrieving email addresses from a database and sending newsletters in PHP, it is important to sanitize the email addresses to prevent SQL injection attacks and validate them to ensure they are in the correct format. Additionally, it is recommended to use a library like PHPMailer to send emails securely and efficiently.

// Retrieve email addresses from database
$stmt = $pdo->prepare("SELECT email FROM users");
$stmt->execute();
$emails = $stmt->fetchAll(PDO::FETCH_COLUMN);

// Sanitize and validate email addresses
$validEmails = [];
foreach ($emails as $email) {
    $sanitizedEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
    if (filter_var($sanitizedEmail, FILTER_VALIDATE_EMAIL)) {
        $validEmails[] = $sanitizedEmail;
    }
}

// Send newsletters using PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your@example.com';
    $mail->Password = 'your_password';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom('your@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com');

    $mail->isHTML(true);
    $mail->Subject = 'Newsletter Subject';
    $mail->Body = 'Newsletter content';

    $mail->send();
    echo 'Newsletter sent successfully';
} catch (Exception $e) {
    echo 'Newsletter could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}