What is the correct way to store and use email addresses from a database in PHP for sending mass emails?

When sending mass emails, it is important to ensure that email addresses are stored securely and used appropriately to comply with privacy regulations. One way to achieve this is by retrieving email addresses from a database in PHP and looping through them to send individual emails. It is also recommended to use a library like PHPMailer to handle the sending of emails securely.

// Retrieve email addresses from the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT email FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $email = $row["email"];
        
        // Use PHPMailer to send email
        require 'PHPMailer/PHPMailer.php';
        require 'PHPMailer/SMTP.php';
        
        $mail = new PHPMailer\PHPMailer\PHPMailer();
        
        $mail->isSMTP();
        $mail->Host = 'smtp.example.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'your@example.com';
        $mail->Password = 'yourpassword';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
        
        $mail->setFrom('your@example.com', 'Your Name');
        $mail->addAddress($email);
        
        $mail->isHTML(true);
        $mail->Subject = 'Your Subject';
        $mail->Body = 'Your Email Body';
        
        if(!$mail->send()) {
            echo 'Message could not be sent.';
            echo 'Mailer Error: ' . $mail->ErrorInfo;
        } else {
            echo 'Message has been sent';
        }
    }
} else {
    echo "0 results";
}

$conn->close();