PHP发送批量邮件

标签 php email batch-file

<分区>

Possible Duplicate:
Sending mass email using PHP

我有一个 PHP 脚本,可以向我的数据库中的所有用户发送单独的电子邮件,例如每月/每周的时事通讯。

我使用的代码如下:

$subject = $_POST['subject'];
$message = $_POST['message'];

// Get all the mailing list subscribers.
$query = $db->prepare("SELECT * FROM maildb");
$query->execute();

// Loop through all susbcribers, and send and individual email.
foreach ($query as $row) {

    // Setting maximum time limit to infinite.
    set_time_limit(0);

    $newMessage = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
        </head>
        <body>';

    // Search for the [unsubscribe] tag and replace it with a URL for the user to unsubscribe
    $newMessage .= str_replace("[unsubscribe]", "<a href='".BASE_URL."unsubscribe/".$row['hash']."/".$row['email']."'>unsubscribe</a>", $message);

    $newMessage .= '</body></html>';

    $to = $row['email'];

    // Establish content headers
    $headers = "From: info@domain.com"."\n";
    $headers .= "Reply-To: bounce@domain.com"."\n";
    $headers .= "X-Mailer: PHP v.". phpversion()."\n";
    $headers .= "MIME-Version: 1.0"."\n";  
    $headers .= "Content-Type: text/html; charset=iso-8859-1"."\n";
    $headers .= "Content-Transfer-Encoding: 8bit;";

    mail($to, $subject, $newMessage, $headers); // Send email to each individual user

}

此代码与一个非常小的数据库完美配合......我最近用 200k+ 用户填充了我的测试数据库,显然这个脚本失败了,内存不足,然后死了......

我知道发送这么多电子邮件是一种糟糕的方式,这就是为什么我想请您提供更有效的方式来做到这一点!

非常感谢!

最佳答案

您遇到的超时是因为 Apache 和 PHP 执行限制。

您需要使用 set_time_limit(0);

作为 CLI 应用程序运行它

php /path/to/app/script.php 直接在控制台中这样的东西。

如果您没有 SSH 访问权限,请像这样使用 shell_exec 运行它:

shell_exec("php /path/to/app/script.php > /dev/null 2>/dev/null &");

这将确保调用它的脚本在完成之前不会挂起。

关于PHP发送批量邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12237628/

相关文章:

javascript - 如何使用 PHP 和 AJAX 从 MySQL 创建 JavaScript 变量?

iphone - 使用来自 Apple 示例的 Mailcomposer 的代码时出错

windows - 计算批处理文件中的已用磁盘空间

vbscript - 更改文件名中的 HOUR。批处理脚本

php - 在 IIS7 集群上运行的 PHP 上调试 500 Internal Server Error

javascript - 如何将 php 数组格式化为 javascript 数组?

php - PHP 中 pthread 的问题

wordpress - 付款后发送邮件 paypal 联系表 7

c# - 重音字符未显示

Windows 批处理循环遍历子文件夹并运行命令