简体   繁体   English

PHP,电子邮件和Cron

[英]PHP, Email and Cron

Let me rephrase my question, I have a mysql database that is holding emails to be sent, on a shared host. 我再说一遍我的问题,我有一个mysql数据库,它在共享主机上保存要发送的电子邮件。 I would like to run a cron job that will read the database and sent out any messages in the database every 10 minutes or so. 我想运行一个cron作业,它将每10分钟左右读取一次数据库并发送出数据库中的所有消息。

Now my question is, what is the best way with php to read my database and send out the emails in small batched so that I don't overwhelm the shared host. 现在我的问题是,用php读取我的数据库并小批量发送电子邮件的最佳方法是什么,这样我才不会淹没共享​​主机。

Assuming the use of PDO, and making some accommodation for not knowing your schema, it might look something like this: 假设使用PDO,并为不了解您的模式做了一些调整,它可能看起来像这样:

$dbh = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'dbuser', 'dbpass');
$msgh = $dbh->prepare('SELECT subject, body from message where listname = :listname');
$msgh->bindParam(':listname', $listname, PDO::PARAM_STR);
$msgh->execute();
$msg = $msgh->fetch(PDO::FETCH_ASSOC);

$usrh = $dbh->prepare('SELECT recipient from userlist where is_subscribed_to = :listname');
$usrh->bindParam(':listname', $listname, PDO::PARAM_STR);
$usrh->execute();
while ($recipient = $usrh->fetch(PDO::FETCH_ASSOC)) {
  mail($recipient, $msg['subject'], $msg['body']);
  if ($over_throttle) {
    sleep(THROTTLE_SLEEP_SECONDS);
    $over_throttle = 0;
  }
  ++$over_throttle;
}

As for 'prewritten', you might take a look at phplist . 至于“预写”,您可以看看phplist

I would leave the throttling to the email server. 我会把限制留给电子邮件服务器。 Ie, run an email server locally, and have your PHP code relay all these messages to that. 即,在本地运行电子邮件服务器,然后让您的PHP代码将所有这些消息中继到该服务器。 Then configure the email server itself to only send out at a certain rate. 然后将电子邮件服务器本身配置为仅以一定速率发送出去。

Well I came up with this solution similar to the PDO one. 好吧,我想出了与PDO类似的解决方案。 Are there any unforeseen problems with running this as a cron job? 将其作为cron作业运行是否有任何无法预料的问题?

<?php
$con = mysql_connect("localhost","root","123456");
$throttle = 0;
$batch = 50;
$pause = 10; // seconds

if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("maildb", $con);

// Message Table
$MSGresult = mysql_query("SELECT * FROM msgs");

// User Table
$USERresult = mysql_query("SELECT * FROM members");

while($MSGrow = mysql_fetch_array($MSGresult))
  {
    while($USERrow = mysql_fetch_array($USERresult))
        {
          mail($USERrow['email'],$MSGrow['subject'],$MSGrow['body']);
          $throttle += 1;
          if ($throttle > $batch ) { sleep($pause); $throttle = 0;} 
        }
    mysql_data_seek($USERresult,0);
  }

mysql_close($con);
?> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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