[Solved] How to send emails in large quantities with PHP script and cronjobs [closed]


You should have a database table with these columns:

===============
Suscribers Table
===============
|id (int)|email (varchar)|sent (tinyint)
|1|[email protected]|0
|2|[email protected]|0
|3|[email protected]|0

Then something like this PHP script:

// DB Connection
require_once 'db.php';

// Check if we have users with a 0 sent value
$query = mysql_query("SELECT COUNT(id) FROM suscribers WHERE sent = 0");
$results = mysql_num_rows($query);

// If there's one or more suscribers with a 0 sent value
if ($results >= 1) {
    // Initialize and require Swift or any other email library for PHP
    require_once 'swift/lib/swift_required.php';
    $transport = Swift_SmtpTransport::newInstance('mail.domain.com', 587)
      ->setUsername('[email protected]')
      ->setPassword('password');
    $mailer = Swift_Mailer::newInstance($transport);

    // Body of the email
    $body = '<html><head></head><body>Hello suscriber!</body></html>'

    // Message parameters
    $message = Swift_Message::newInstance();
    $message->setSubject('Newsletter');
    $message->setFrom(array('[email protected]' => 'Domain Newsletter'));
    $message->setSender('[email protected]');
    $message->setBody($body, 'text/html');

    // Use a query to get only 100 suscribers from the table who have a 0 sent value
    $query = mysql_query("SELECT id, email FROM suscribers WHERE sent = 0 LIMIT 100");
    while ($data = mysql_fetch_array($query)) {
        $idEmail = $data['id'];
        $message->setTo($data['email']);

        // Update the email sender ID "sent" value to "1"
        mysql_query("UPDATE suscribers SET sent = 1 WHERE id = $idEmail");
        $mailer->send($message);
    }
}

Finally use a cron job like this one that points to your PHP cron file:

/usr/bin/php -q /home/domain/public_html/newsletter_cron.php

solved How to send emails in large quantities with PHP script and cronjobs [closed]