Search code examples
phpphpmailer

PHP - Sending emails to every user with a certain id


Currently, I am able to send emails to every user in the database with a certain id, but it takes a while for the function to run, and therefore making the browser wait until it finishes.

Is there a way to have the email sending function run somewhere else, and have the page move on so the user doesn't have to wait.

This is a concern, because if there are many users to send emails too, then this process may take way too long and have the user wait just as long.

My current code is as follows.

{

$sql_query = "SELECT * FROM `influencers` WHERE `brand_id` = $brand_id";
$i = 0;
$queryResult = mysqli_query($conn, $sql_query);
while($i<mysqli_num_rows($queryResult) ) {
    $inf_info = mysqli_fetch_assoc($queryResult);
    $brand = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM `brands` WHERE `id` = '$brand_id'"));
    $mail = new PHPMailer();
    $mail->isSMTP();
    $mail->Host = "smtp.gmail.com";
    $mail->SMTPAuth = true;
    $mail->Username = 'PLACEHOLDEREMAIL@gmail.com';
    $mail->Password = 'PLACEHOLDERPASSWORD';
    $mail->SMTPSecure = "ssl";
    $mail->Port = 465;
    $mail->SetFrom(EMAIL_USERNAME, "Support");
    $mail->addAddress($inf_info['email'], $inf_info['first_name'] . " " . $inf_info['last_name']);
    $mail->Subject = "Your insider brand has started an internal campaign!";
    $mail->isHTML();
    $mail->Body = "
        Greetings influencer! We want to let you know that that your insider brand, " . $brand['name'] . ",<br><br>

        Has started a new insider campaign.<br><br>

        If you wish to not participate, simply ignore this email.<br><br>

        Sincerely,<br><br>

        The Crowdfluence Team
    ";
    // Check if email was sent successfully
    if ($mail->send()){
        unset($mail);
    }else{
        unset($mail);
    }
    $i +=1;
}

}

Solution

  • Creating a cron job is what you need for this sort of thing, basically have a background process running on your server with which you can then call a function whenever you want. You can save the details of your email into the database into a table instead of sending each email for each user and let the user carry on with what they are doing, then using the cron job call a php function to go through that table, pull down the details of the email and send them.

    So what you might end up doing is writing a cron job that runs every 5 minutes to call a sendEmails link that will run the process that you need.

    */5 * * * * wget http://example.com/sendEmails