简体   繁体   中英

PHPMailer hangs on sending bulkmails

I had successfully set up a web app using PHP, PHPmailer on centos server for sending bulk emails to customers. customer emails get from SQL database. It successfully works and it sends one email and sleeps 20 seconds, then do this process as a loop. The database has 6000 email addresses. In this process, the server hangs by sending about 100 emails. So I have to run this program again. Why does this hang? I don't get a PHP error or a PHP timeout.

This is my code:`

<?php

require 'PHPMailerAutoload.php';
$con = mysql_connect("localhost", "root", "test");
mysql_select_db("user", $con);
$query = "select email from client_detail";
$result = mysql_query($query, $con);
$email = array();
while ($row = mysql_fetch_assoc($result)) {
    $email[] = $row['email'];
}
foreach ($email as $to) {
    $mail = new PHPMailer;
    $mail->setFrom('bestweb@nic.lk');
    $mail->addAddress($to);
    $mail->Subject = 'Bestweb2018';
    $mail->isHTML(true);
    $mail->Body = '<html>
                        <head>
                            <title>BestWeb.lk 2018</title>
                        </head>
                        <body>
                            <table style="width: 760px;" >
                                <tr>
                                    <td>
                                        <img src="cid:banner" alt="bestweb.lk 2018" width="760px" height="167px" /> 
                                    </td>
                                </tr>
                                </table>
                              </body>
                    </html>
            ';
    $mail->AddEmbeddedImage('images/bannergold.gif', 'banner');

    if (!$mail->send()) {
        echo 'Message was not sent ' . $to;
        echo "<br>";
        echo 'Mailer error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent ' . $to;
        echo "<br>";
    }

    sleep(20);
}
?>

The server can be overloaded because of 20 seconds sleep sleep(20) for each iteration.

Reduce sleep time to few seconds like 2 or 3.

sleep(3)

Enable display errors, add this top of the script

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Log email completion status on log file because you are running a loop all echo data goes to buffer so nothing would get print until loop gets finished.

if (!$mail->send()) {
    @file_put_contents('email-logs.txt', 'Message was not sent ' . $to ." - error :" . var_export( $mail->ErrorInfo, true) . "\n", FILE_APPEND);
} else {
    @file_put_contents('email-logs.txt', 'Message has been sent ' . $to . "\n", FILE_APPEND);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM