如何使用PHP脚本和cronjobs大量发送电子邮件

时间:2014-01-30 03:50:55

标签: php email cron sendmail send

我需要向8000位订阅者发送简报,但我的主持人只支持每小时发送100封邮件。我需要一个完成这项工作的PHP脚本,每小时发送8000封电子邮件,每封限制100封电子邮件,如果可能的话,使用cronjobs,而不必在脚本运行时保持浏览器打开。

由于

1 个答案:

答案 0 :(得分:0)

您应该有一个包含以下列的数据库表:

===============
Suscribers Table
===============
|id (int)|email (varchar)|sent (tinyint)
|1|example1@domain.com|0
|2|example2@domain.com|0
|3|example3@domain.com|0

然后像这样的PHP脚本:

// 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);
    }
}

最后使用像这样指向PHP cron文件的cron作业:

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