如何使用PHP脚本和cronjobs大量发送电子邮件 [英] How to send emails in large quantities with PHP script and cronjobs

查看:119
本文介绍了如何使用PHP脚本和cronjobs大量发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

感谢

推荐答案

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

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

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

最后使用cron作业,您的PHP cron文件:

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

这篇关于如何使用PHP脚本和cronjobs大量发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆