我的網站每當有人發短信(私信)時,都會向我的用戶發送一封電子郵件。它表示的內容是「有人在站點名稱上向您發送了一條消息,請登錄查看」。什麼是通過PHP向大量用戶發送電子郵件的最有效方式?
此刻我的網站是不是很受歡迎,所以我現在這樣的方式一直沒有問題的表現明智的:
發送一個PM// code that sends pm here...
// code that stores pm in messages table here...
// notify user by emailing them right away
mail($user_email, $subject, $message);
基本上每次執行郵件功能並在當場發送信息。因此,每發送100封郵件,郵件()就會被調用100次。
我期待我的網站越來越受歡迎,並且隨着更多的用戶來到更多的PM,所以我認爲我目前的做法會成爲一場性能噩夢。所以我在想這樣做,而不是這樣的:
// get the last message that was accounted for by the last cron
$query = mysql_query(" SELECT `last_checked_id` FROM `settings` ");
$last_checked_id = mysql_fetch_array($query);
$user_emails = array();
// get all messages that were added to this table since the last time this cron ran
$query = mysql_query(" SELECT `recipient_id`, `message_id` FROM `messages` WHERE `message_id` > '$last_checked_id' ");
$i = 0;
while($row = mysql_fetch_array($query)) {
if($i == 0) {
// set this as the last message processed
mysql_query(" UPDATE `settings` WHERE `last_checked_id` = '". $row['message_id'] ."' ");
}
// only put this user in the to email list if he hasn't been added already (since there can be multiple messages for the same user but we need to notify him only once)
if(!in_array($row['recipient_id'], $user_emails)) {
array_push($user_emails, $row['recipient_id']);
}
}
$i++;
// send email to all users at one
mail(implode(',', $user_emails), $subject, $message);
我可以將這個腳本爲計劃並運行它每隔一小時。所有的電子郵件都是一次發送的,郵件功能只被調用一次。唯一的缺點是用戶在他們收到PM時不會立即通知,而是在一小時內收到通知。但這並不是什麼大事,我可以忍受。
我的問題是:
- 是cron的方法顯著更好的性能明智或增加微不足道
- 這是多數大網站做到這一點?還是有更好的方法,一些已建立的圖書館可能會再見?
謝謝。從表
關於SO最低調的PHP問題可能有一些見解http://stackoverflow.com/questions/3905734/how-to-send-100-000-emails-weekly – 2012-04-18 20:11:06
相關:我也會限制一些電子郵件(如線程回覆通知),以便他們不會突然收到10封電子郵件,並告訴他們同一個線索已被評論。 – Xeoncross 2012-04-18 20:11:21