Search code examples
phphtmlmysqlmysqliphpmailer

How can I get recipients for phpmailer from a mysql database?


Basically I have a table in a db with name and email address fields. How can I get this info from the db and insert each email address into a $mail->AddAddress('xxxxx');

Edit: I have phpmailer working properly but I am not even sure where to start as far as getting the addresses from the table and using them as the recipients. This is my first project using mysqli. Any help to point me in the right direction would be much appreciated.


Solution

  • The way is to retrieve data from the DB and send a new email with every loop. Please be aware that some hosters reqire some milliseconds break between the emails.

    Here is an example:

        <?php
    $pdo = new PDO('mysql:host=localhost;dbname=mydb', 'root', '');
    $sql = "SELECT email FROM users";
    
        foreach ($pdo->query($sql) as $row) {
            $mail = new PHPMailer\PHPMailer\PHPMailer();
            $mail->IsSMTP(); // enable SMTP
            $mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only, 0 = nothing
            $mail->CharSet = "UTF-8";
            $mail->SMTPAuth = true; // authentication enabled
            $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
            $mail->Host = 'your_email_host';
            $mail->Port = 465; // or 587
            $mail->IsHTML(true);
            $mail->Username = 'your_emailaccount_username';
            $mail->Password = 'your_emailaccount_password';
            $mail->SetFrom('[email protected]', 'from_name');
            $mail->Subject = 'Your Email Subject';
            $mail->Body = $body_combined;
            $mail->AddAddress($row['email']); // dynamic email from DB with every loop
        }