I need to send a newsletter to 8000 subscribers, but my host only supports sending 100 messages per hour. I need a php script that does this job, send 8000 emails with a limit of 100 emails per hour, if possible using cronjobs for me not having to keep the browser open while the script is running.
Thanks
You should have a database table with these columns:
===============
Suscribers Table
===============
|id (int)|email (varchar)|sent (tinyint)
|1|example1@domain.com|0
|2|example2@domain.com|0
|3|example3@domain.com|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('mail@domain.com')
->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('mail@domain.com' => 'Domain Newsletter'));
$message->setSender('mail@domain.com');
$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